本文以一个实例形式介绍了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 } }