DelphiFAQ Home Search:
General :: Windows :: Programming :: Windows with Delphi :: Windows API
Windows programming with Delphi

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Only the 40 most recently viewed articles are shown.
You can see the full list here.

Featured Article

Programmatically logoff a user, shutdown or reboot

If your program needs to programmatically logoff a user, shutdown or reboot the computer, then you may use the following function with the appropriate parameter:

WinExit(EWX_LOGOFF); // one of these 3 only :-)
WinExit(EWX_REBOOT);
WinExit(EWX_SHUTDOWN);

See the source for the flags EWX_POWEROFF and EWX_FORCE.
The function SetPrivilege() is a necessary helper function.
The other document referenced at the top in the See-Also section is a slight modification of this code snippet, but it works basically the same way.

function SetPrivilege (sPrivilegeName: string; bEnabled: Boolean) : Boolean;
 var
   TPPrev,
   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 (sPrivilegeName), TP.Privileges[0].LUID) then 
   begin 
     if bEnabled 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; 
 
 
 // 
 // iFlags: 
 // 
 //  one of the following must be 
 //  specified 
 // 
 //   EWX_LOGOFF 
 //   EWX_REBOOT 
 //   EWX_SHUTDOWN 
 // 
 //  following attributes may be 
 //  combined with above flags 
 // 
 //   EWX_POWEROFF 
 //   EWX_FORCE    : terminate processes 
 // 
 function WinExit (iFlags: integer) : Boolean; 
 begin 
   result := true; 
   if SetPrivilege ('SeShutdownPrivilege', true) then 
   begin 
     if (not ExitWindowsEx (iFlags, 0)) then 
     begin 
       // handle errors... 
       result := False 
     end; 
     SetPrivilege ('SeShutdownPrivilege', False) 
   end 
   else 
   begin 
     // handle errors... 
     result := False 
   end 
 end; 
 
You don't like the formatting? Check out SourceCoder then!