本文以一個執行個體形式介紹了VC++簡單實現關機、重啟電腦的方法,代碼比較實用,有一定的參考價值。完整執行個體代碼如下:
void CWebBrowserView::OnMenuShutdown(){ // TODO: 在此添加命令處理常式代碼 if (AfxMessageBox("確定要關機嗎?",MB_YESNO) == IDYES) { HANDLE hToken; TOKEN_PRIVILEGES tkp; // Get a token for this process. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { AfxMessageBox("OpenProcessToken Error!"); return; } // 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, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, NULL); if (GetLastError() != ERROR_SUCCESS) { AfxMessageBox("關機失敗"); return; } // Shut down the system and force all applications to close. ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, 0); //重啟只需要把EWX_SHUTDOWN改為EWX_REBOOT }}