c++ - 如何在 VC++ 的 Windows 7 或 Windows 8 中延迟关机/重启/休眠

标签 c++ windows visual-studio-2012

我正在使用使用 C++ 开发的基于 vs2012 的应用程序。

如果应用程序正在运行并进行一些处理,并且用户触发重启/关机或休眠,则重启/关机应该暂停,直到应用程序处理完成。

应用程序处理完成后,Windows 应恢复重启/关闭。

如果可以提供一些引用或示例代码,我将不胜感激

谢谢

最佳答案

我做了这样的事情

bool shutdownSystemWin(EShutdownActions action)
{
    HANDLE hToken;
    TOKEN_PRIVILEGES tkp;

    // Get a token for this process.
    if (!OpenProcessToken(GetCurrentProcess(),
        TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
        return false;

    // Get the LUID for the shutdown privilege.
    LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
        &tkp.Privileges[0].Luid);

    tkp.PrivilegeCount = 1;  // one privilege to set
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    // Get the shutdown privilege for this process.
    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
        (PTOKEN_PRIVILEGES)NULL, 0);

    if (GetLastError() != ERROR_SUCCESS)
        return false;

    // Shut down the system and force all applications to close.
    UINT flags = EWX_FORCE;
    switch (action)
    {
    case EShutdownActions::Shutdown:
        flags |= EWX_SHUTDOWN;
        break;
    case EShutdownActions::PowerOff:
        flags |= EWX_POWEROFF;
        break;
    case EShutdownActions::SuspendToRAM:
        return SetSuspendState(FALSE, FALSE, FALSE);
    case EShutdownActions::Hibernate:
        return SetSuspendState(TRUE, FALSE, FALSE);
        break;
    case EShutdownActions::Reboot:
        flags |= EWX_REBOOT;
        break;
    case EShutdownActions::LogOff:
        flags |= EWX_LOGOFF;
        break;
    }

    if (!ExitWindowsEx(flags,
        SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
        SHTDN_REASON_MINOR_UPGRADE |
        SHTDN_REASON_FLAG_PLANNED))
        return false;

    //shutdown was successful
    return true;
}

关于c++ - 如何在 VC++ 的 Windows 7 或 Windows 8 中延迟关机/重启/休眠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31298805/

相关文章:

C++:如何阻止 .msc 和 .cpl 类型的应用程序?

c++ - 尝试连接到 MessageBeep 系统 API

c++ - 插入 STL 映射结构元素

c++ - 有没有办法在 C++ 泛型类中透明地包装可比较的 C 结构?

windows - 从 Linux 连接到 Windows 来执行任务

Java:写入 Windows 临时目录中的 tempFile

visual-studio-2012 - 未保存 Nuget 包源

C语言返回类型

c# - WPF VS2013 : An error occurred while finding the resource dictionary

c++ - 返回引用时的 std::vector::emplace_back 错误 (C++17)