如何在vc++中延迟windows 7或windows 8的关机/重启/休眠

How to delay shutdown/restart/hibernate in windows 7 or windows 8 in VC++

本文关键字:windows 休眠 关机 重启 vc++ 延迟      更新时间:2023-10-16

我使用的是基于vs2012的应用程序,使用c++开发。

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

一旦应用程序处理完成,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;
}