如何在Windows 7或Windows 8中使用VC++延迟关机/重启/休眠

3

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

如果应用程序正在运行并进行某些处理,而用户触发重新启动/关闭或休眠,则重新启动/关闭应该被暂停,直到应用程序处理完成为止。

一旦应用程序处理完成,Windows 应该恢复到重新启动/关闭状态。

如果有关于此问题的参考或示例代码,我将不胜感激。

谢谢!


1
我不会关闭这个问题,因为它非常具体,针对一些晦涩的Windows API协议(可能是一个灰色地带)。 - user2249683
1个回答

2

我做了类似这样的事情


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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接