Title: A simple component to reboot, shutdown and logoff a system.
Question: Need an easy way to reboot, shutdown, logoff a system? That's: easy and fast.
Answer:
Unit uSystemReboot;
Interface
Uses
Windows, Classes;
Type
TWRAction = ( twraLogOff, twraReboot, twraShutDown );
TWRFlags = Set Of ( twraPowerOff, twraForce );
TSystemReboot =
Class( TComponent )
Private
FAction : TWRAction;
FFlags : TWRFlags;
Function SetPrivilege( PrivilegeName : String; Enable : Boolean ) : Boolean;
Public
Function WinExit( Flags : Integer ) : Boolean; OverLoad;
Function WinExit : Boolean; OverLoad;
Published
Property Action : TWRAction Read FAction Write FAction;
Property Flags : TWRFlags Read FFlags Write FFlags;
End;
Procedure Register;
Implementation
Function TSystemReboot.SetPrivilege( PrivilegeName : String; Enable : Boolean ) : Boolean;
Var
tpPrev : TTokenPrivileges;
tp : TTokenPrivileges;
Token : THandle;
dwRetLen : DWord;
Begin
Result := False;
OpenProcessToken( GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, Token );
tp.PrivilegeCount := 1;
If ( LookupPrivilegeValue( NIL, PChar( PrivilegeName ), tp.Privileges[ 0 ].LUID ) ) Then Begin
If ( Enable ) Then
tp.Privileges[ 0 ].Attributes := SE_PRIVILEGE_ENABLED
Else
tp.Privileges[ 0 ].Attributes := 0;
dwRetLen := 0;
Result := AdjustTokenPrivileges( Token, False, tp, SizeOf( tpPrev ), tpPrev, dwRetLen );
End;
CloseHandle( Token );
End;
Function TSystemReboot.WinExit( Flags : Integer ) : Boolean;
Begin
Result := True;
SetPrivilege( 'SeShutdownPrivilege', True );
If ( Not( ExitWindowsEx( Flags, 0 ) ) ) Then Result := False;
SetPrivilege( 'SeShutdownPrivilege', False );
End;
Function TSystemReboot.WinExit : Boolean;
Var
Flags : Word;
Begin
Result := True;
SetPrivilege( 'SeShutdownPrivilege', True );
Case FAction Of
twraLogOff : Flags := EWX_LOGOFF;
twraReboot : Flags := EWX_REBOOT;
Else
Flags := EWX_SHUTDOWN;
End;
If ( twraPowerOff In FFlags ) Then Flags := Flags Or EWX_POWEROFF;
If ( twraForce In FFlags ) Then Flags := Flags Or EWX_FORCE;
If ( Not( ExitWindowsEx( Flags, 0 ) ) ) Then Result := False;
SetPrivilege( 'SeShutdownPrivilege', False );
End;
Procedure Register;
Begin
RegisterComponents( 'Christian', [ TSystemReboot ] );
End;
End.