ExitWindowsEx 实现关机、重启

本文介绍Windows API中的ExitWindowsEx函数,该函数用于注销当前用户、关闭系统或重启系统。文章详细解释了函数参数uFlags和dwReason的作用,并提供了一个使用示例。

ExitWindowsEx

 

The ExitWindowsEx function either logs off the current user, shuts down the system, or shuts down and restarts the system. It sends the WM_QUERYENDSESSION message to all applications to determine if they can be terminated.

 
BOOL ExitWindowsEx(
  UINT uFlags,
  DWORD dwReason
);

 

uFlags
[in] Shutdown type. This parameter must include one of the following values.  关机类型
EWX_LOGOFF
EWX_POWEROFF
EWX_REBOOT
EWX_SHUTDOWN
可选的参数
EWX_FORCE       强制进程终止 不发送 WM_QUERYENDSESSION and WM_ENDSESSION消息
EWX_FORCEIFHUNG 发送 WM_QUERYENDSESSION and WM_ENDSESSION消息,如果没有响应强制终止进程。
dwReason
[in] Reason for initiating the shutdown.
If this parameter is zero, the SHTDN_REASON_FLAG_PLANNED reason code will not be set, and therefore the default action is an undefined shutdown that is logged as "No title for this reason could be found". By default, it is also an unplanned shutdown. Depending on how the system is configured, an unplanned shutdown triggers the creation of a file that contains the system state information, which can delay shutdown. Therefore, do not use zero for this parameter.

示例:

 

The following example enables the SE_SHUTDOWN_NAME privilege and then shuts down the system.

BOOL MySystemShutdown()
{
   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, 0)) 
      
return FALSE; 

   
return TRUE;
}

 

 注意,如果不实现设置权限 会导致调用失败。

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值