DelphiFAQ Home Search:

Programmatically logoff a user, shutdown or reboot

 

comments2 comments. Current rating: 3 stars (1 votes). Leave comments and/ or rate it.

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!

Comments:

2006-09-27, 06:24:33
anonymous from Bulgaria  
rating
How can you log off specific user
2007-08-30, 14:13:26
anonymous from India  
its a good code

 

 

Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:
photo Add a picture:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity. The owner of this web site reserves the right to delete such material.