1. 在头文件中加入成员变量
public:
BOOL fResult;
TOKEN_PRIVILEGES tkp;
HANDLE hToken;
2. 关机代码
if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
MessageBox(_T("OpenProcessToken failed!"));
}
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid); //获得本地机唯一的标识
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0); //调整获得的权限
if (GetLastError() != ERROR_SUCCESS)
{
MessageBox(_T("AdjustTokenPrivileges enable failed!"));
}
fResult =InitiateSystemShutdown(
NULL, // 要关的计算机用户名
_T("由于系统不稳定,WINDOWS将在上面的时间内关机,请做好保存工作!"), // 显示的消息
10, // 关机所需的时间
TRUE, // ask user to close apps
TRUE); //设为TRUE为重起,设为FALSE为关机
if(!fResult)
{
MessageBox(_T("InitiateSystemShutdown failed."));
}
tkp.Privileges[0].Attributes = 0;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0);
if (GetLastError() != ERROR_SUCCESS)
{
MessageBox(_T("AdjustTokenPrivileges disable failed."));
}
ExitWindowsEx(EWX_SHUTDOWN,0);