windows关机API

NT系统的关机API函数实现过程

前计算机系统多为Windows 2000和Windows XP。Windows 98系统下的关机比较容易,只需要直接调用关闭计算机函数ExitWindowEx就可以了,而在Windows 2000系统下的调用这个函数只能“注销”而不能实现系统关机。在Windows 2000系统实现关机操作得到SHUTDOWN许可,得到SHUTDOWN许可需要调用相应的API函数,具体过程如下:

(1)首先得到当前程序的进程句柄;
(2)使用这个进程句柄得到当前程序的访问标记;
(3)生成TOKEN_PRIVILEGES结构;
(4)有了TOKEN_PRIVILEGES结构后再获得SHUTDOWN权限;
(5)最后使用ExitWindowEx函数进行相关操作。
1) 相关的API函数
    获得当前进程伪句柄函数GetCurrentProcess,函数声明如下:
    Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
    取得程序访问标记函数OpenProcessToken,函数声明如下:
    Private Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
   查找进程权限函数LookupPrivilegeValue,函数声明如下:
   Private Declare Function LookupPrivilegeValue Lib "advapi32" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, lpLuid As LUID) As Long
   获得关机权限函数AdjustTokenPrivileges,函数声明如下:
   Private Declare Function AdjustTokenPrivileges Lib "advapi32" (ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long
   关机函数ExitWindowEx
   Private Declare Function ExitWindowsEx Lib "user32" Alias "ExitWindowsEx" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long
     用于关机操作的一些常数如表2所示

常数值
字符标识
作用
&H20
TOKEN_ADJUST_PRIVILEGES
关机权限标识
&H8
TOKEN_QUERY
标识查询
&H2
SE_PRIVILEGE_ENABLED
私有进程有效
0
EWX_LOGOFF
终止进程系统注销
1
EWS_SHUTDOWN
关闭系统电源
2
EWS_REBOOT
重新启动
4
EWS_FORCE
强行终止没有响应的进程


 [C/C++]代码

01 //关闭计算机
02 BOOL MySystemShutdown()
03 {
04    HANDLE hToken;
05    TOKEN_PRIVILEGES tkp;
06   
07    // Get a token for this process.
08   
09    if (!OpenProcessToken(GetCurrentProcess(),
10         TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
11       return( FALSE );
12   
13    // Get the LUID for the shutdown privilege.
14   
15    LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
16         &tkp.Privileges[0].Luid);
17   
18    tkp.PrivilegeCount = 1;  // one privilege to set   
19    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
20   
21    // Get the shutdown privilege for this process.
22   
23    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
24         (PTOKEN_PRIVILEGES)NULL, 0);
25   
26    if (GetLastError() != ERROR_SUCCESS)
27       return FALSE;
28   
29    // Shut down the system and force all applications to close.
30   
31    if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
32                SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
33                SHTDN_REASON_MINOR_UPGRADE |
34                SHTDN_REASON_FLAG_PLANNED))
35       return FALSE;
36  
37    return TRUE;
38 }

你可能感兴趣的:(windows,String,function,api,query,token)