1. 程式人生 > >Qt5實現系統關機和重啟的功能

Qt5實現系統關機和重啟的功能

最近公司的專案需要軟體自帶系統關機和重啟的功能,因此在msdn搜尋了一下實現方法,windows下直接使用下列程式碼就可以了

xxx.h檔案中新增

BOOL  MySystemShutdownOrRestart();

xxx.cpp檔案中新增

#include<windows.h>

BOOL MainWindow::MySystemShutdownOrRestart()

{
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. 
        /*
if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
SHTDN_REASON_MINOR_UPGRADE |

SHTDN_REASON_FLAG_PLANNED))

*/

//restart the system
if (!ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0))
return FALSE;

//shutdown or restart was successful
return TRUE;

}

以後公司專案可能會換到Linux,到時候更新Linux下的系統關機重啟方法。