unit ShutdownUnit;<br>{关机}<br><br>interface<br>uses<br> Windows, Messages;<br><br>procedure ShutDown;<br><br>implementation<br><br>function GetOSType(out AoIsNT : Boolean) : string;<br>var<br> osinfo : OSVERSIONINFO;<br>begin<br> AoIsNT := False;<br> osinfo.dwOSVersionInfoSize := sizeof(OSVERSIONINFO);<br> GetVersionEx(osinfo);<br> with osinfo do begin<br> case dwPlatformid of<br> 0: Result := 'Windows 3.11';<br> 1: begin<br> case dwMinorVersion of<br> 0: Result := 'Windows 95';<br> 10: begin<br> if (szCSDVersion[1] = 'A') then<br> Result := 'Windows 98 SE'<br> else<br> Result := 'Windows 98';<br> end;<br> 90: Result := 'Windows ME';<br> else<br> Result := 'Unknown Version';<br> end;<br> end;<br> 2: begin<br> AoIsNT := True;<br> case dwMajorVersion of<br> 3: Result := 'Windows NT';<br> 4: Result := 'Windows NT';<br> 5: begin<br> case dwMinorVersion of<br> 0: Result := 'Windows 2000';<br> 1: Result := 'Windows XP';<br> end;<br> end;<br> else<br> Result := 'Unknown Version';<br> end;<br> end;<br> else<br> Result := 'Unknown Platform';<br> end;<br> end;<br>end;<br><br>procedure ShutDown_NT;<br> procedure AdjustToken;<br> var<br> hdlProcessHandle : Cardinal;<br> hdlTokenHandle : Cardinal;<br> tmpLuid : Int64;<br> tkp : TOKEN_PRIVILEGES;<br> tkpNewButIgnored : TOKEN_PRIVILEGES;<br> lBufferNeeded : Cardinal;<br> Privilege : array[0..0] of _LUID_AND_ATTRIBUTES;<br> begin<br> hdlProcessHandle := GetCurrentProcess;<br> OpenProcessToken(hdlProcessHandle,(TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY),hdlTokenHandle);<br> LookupPrivilegeValue('', 'SeShutdownPrivilege', tmpLuid);<br> Privilege[0].Luid := tmpLuid;<br> Privilege[0].Attributes := SE_PRIVILEGE_ENABLED;<br> tkp.PrivilegeCount := 1; // One privilege to set<br> tkp.Privileges[0] := Privilege[0];<br> AdjustTokenPrivileges(hdlTokenHandle, False, tkp, Sizeof(tkpNewButIgnored), tkpNewButIgnored, lBufferNeeded);<br> end;<br>var<br> hProcess,hAccessToken:THandle;<br> LUID_AND_ATTRIBUTES:TLUIDAndAttributes;<br> TOKEN_PRIVILEGES: TTokenPrivileges;<br> BufferIsNull
WORD;<br>Const<br> SE_SHUTDOWN_NAME='SeShutdownPrivilege';<br>begin<br> hProcess := GetCurrentProcess();<br> OpenProcessToken(hprocess, TOKEN_ADJUST_PRIVILEGES+TOKEN_QUERY, hAccessToken);<br> LookupPrivilegeValue(Nil,SE_SHUTDOWN_NAME,LUID_AND_ATTRIBUTES.Luid);<br> LUID_AND_ATTRIBUTES.Attributes:=SE_PRIVILEGE_ENABLED;<br> TOKEN_PRIVILEGES.PrivilegeCount:=1;<br> TOKEN_PRIVILEGES.Privileges[0]:=LUID_AND_ATTRIBUTES;<br> BufferIsNull:=0;<br> AdjustTokenPrivileges(hAccessToken,False,TOKEN_PRIVILEGES,sizeof(TOKEN_PRIVILEGES),Nil,BufferIsNull);<br> ExitWindowsEx(EWX_POWEROFF or EWX_FORCE, 0);<br>end;<br><br>procedure ShutDown_NotNT;<br>begin<br> ExitWindowsEx((EWX_SHUTDOWN or EWX_FORCE), 0);<br>end;<br><br>procedure ShutDown;<br>var<br> sOSType : string;<br> IsNT : Boolean;<br>begin<br> SendMessage(HWND_BROADCAST, WM_QUERYENDSESSION, 0, 0);<br> sOSType := GetOSType(IsNT);<br> if IsNT then ShutDown_NT<br> else ShutDown_NotNT;<br>end;<br><br>end.