下面代码演示使用InitiateSystemShutdown函数来重启本地系统。系统会显示出一个对话框,显示特定信息,通知用户在指定时间内关闭所有程序。超过指定的时间,系统会重启。
如果在 InitiateSystemShutdown指定的时间内调用了 AbortSystemShutdown,系统不会重启。例如,如果在 MySystemShutdown之后调用了PreventSystemShutdown,系统会闭关对话框,且不会重启系统。
在调用InitiateSystemShutdown之前,需要获取SE_SHUTDOWN_NAME权限。
#include <windows.h>
#pragma comment( lib, "advapi32.lib" )
BOOL MySystemShutdown( LPTSTR lpMsg )
{
HANDLE hToken; // handle to process token
TOKEN_PRIVILEGES tkp; // pointer to token structure
BOOL fResult; // system shutdown flag
// Get the current process token handle so we can get shutdown
// privilege.
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return FALSE;
// Get the LUID for 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 shutdown privilege for this process.
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES) NULL, 0);
// Cannot test the return value of AdjustTokenPrivileges.
if (GetLastError() != ERROR_SUCCESS)
return FALSE;
// Display the shutdown dialog box and start the countdown.
fResult = InitiateSystemShutdown(
NULL, // shut down local computer
lpMsg, // message for user
30, // time-out period, in seconds
FALSE, // ask user to close apps
TRUE); // reboot after shutdown
if (!fResult)
return FALSE;
// Disable shutdown privilege.
tkp.Privileges[0].Attributes = 0;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES) NULL, 0);
return TRUE;
}
如果在 InitiateSystemShutdown指定的时间内调用了 AbortSystemShutdown,系统不会重启。例如,如果在 MySystemShutdown之后调用了PreventSystemShutdown,系统会闭关对话框,且不会重启系统。
BOOL PreventSystemShutdown()
{
HANDLE hToken; // handle to process token
TOKEN_PRIVILEGES tkp; // pointer to token structure
// Get the current process token handle so we can get shutdown
// privilege.
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return FALSE;
// Get the LUID for 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 shutdown privilege for this process.
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES)NULL, 0);
if (GetLastError() != ERROR_SUCCESS)
return FALSE;
// Prevent the system from shutting down.
if ( !AbortSystemShutdown(NULL) )
return FALSE;
// Disable shutdown privilege.
tkp.Privileges[0].Attributes = 0;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES) NULL, 0);
return TRUE;
}
int main()
{
MySystemShutdown("shutdown?");
//Sleep(5000);
//PreventSystemShutdown();
return 0;
}
====
还可以用ExitWindowsEx来重启或关闭系统。ExitWindowsEx在初始化 关闭进程 后就返回, 关闭进程 是异步进行。这个函数用来结束其调用用户的登陆会话,所以如果你不是当前的登陆用户的话,调用这个函数会返回成功但并不会实际地重启或关闭系统。这时就需要用InitiateSystemShutdown或InitiateSystemShutdownEx。