Mega Code Archive

 
Categories / Delphi / System
 

Adjust the windows nt privileges to reboot

If you need to reboot the PC in Delphi 3 on a Windows NT machine, you need to get the right privileges for this. The following code provides a procedure to adjust the privileges and then boots the PC. Unit BootNT; // uses .... Interface Function AdjustTokenPrivileges (TokenHandle: THandle; DisableAllPrivileges: BOOL; Const NewState: TTokenPrivileges; BufferLength: DWORD; PreviousState: PTokenPrivileges; ReturnLength: PWORD) : BOOL; Stdcall; Implementation Function AdjustTokenPrivileges; External 'advapi32.dll' Name 'AdjustTokenPrivileges'; {$R *.DFM} Procedure RebootWindowsNT; Const AdjustMsg = 'Could not adjust the Privilege.' + #13#10; TokenMsg = 'Could not open the Token.' + #13#10; FailMsg = 'Rebooting Windows is failed'; Var Success : Boolean; TokenPriv : TTokenPrivileges; TokenHandle : THandle; CurrentProc : THandle; Begin Success := False; CurrentProc := GetCurrentProcess; If OpenProcessToken (CurrentProc, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, TokenHandle) Then Begin // get privilege If LookupPrivilegeValue (Nil, 'SeShutdownPrivilege', TokenPriv.Privileges[0].LUID) Then Begin TokenPriv.PrivilegeCount := 1; TokenPriv.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; // Reboot system If AdjustTokenPrivileges (TokenHandle, False, TokenPriv, 0, Nil, Nil) Then Success := ExitWindowsEx (EWX_REBOOT, 0); If not Success Then ShowMessage (AdjustMsg + FailMsg) End End Else ShowMessage (TokenMsg + FailMsg); End; Procedure TForm1.Button1Click (Sender: TObject); Begin RebootWindowsNT; End; End.