How to Shut Down, Restart or Log Off the System

2 03 2009

description

 

 

It is very interesting to write your own application to Shut Down, Restart or Log Off the system. right? Its not a big task. Very simple to make it. 🙂

howcanidoit

 

 

Simply use the Win32 API ExitWindowsEx to do this. It sends the WM_QUERYENDSESSION to all applications to determine if they can be terminated.

BOOL ExitWindowsEx(UINT uFlags, DWORD dwReason)

uFlags tells what to do. Different values possible are.

1) EWX_LOGOFF

2) EWX_POWEROFF

3) EWX_REBOOT

4) EWX_RESTARTAPPS

5) EWX_SHUTDOWN

dwReason – indicates the reason for initiating the shutdown.

mycodesnippet

 

 

void ToShutdownMySystem()
{
   HANDLE hToken;
   TOKEN_PRIVILEGES tkp;
  
   // Get a token for this process.   
   if (!OpenProcessToken(GetCurrentProcess(),
      TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
      AfxMessageBox("Failed to get the token for this process");
  
   // Get the LUID for the shutdown privilege.   
   LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
  
   tkp.PrivilegeCount = 1;  // one privilege to set   
   tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  
   // Get the shutdown privilege for this process.
  
   AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
      (PTOKEN_PRIVILEGES)NULL, 0);
  
   if (GetLastError() != ERROR_SUCCESS)
      AfxMessageBox("Failed to adjust the token privileges.");
  
   // Shut down the system and force all applications to close.   
   if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
      SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
      SHTDN_REASON_MINOR_UPGRADE |
      SHTDN_REASON_FLAG_PLANNED))
      AfxMessageBox("Failed to Shut Down the system.");
  
}

 mynote1

 

 

To shut down or restart the system, the calling process must use the AdjustTokenPrivileges function to enable the SE_SHUTDOWN_NAME privilege.

Advertisements

Actions

Information

One response

19 01 2011
Logan

This code doesn’t work with C++.
I keep getting Expected primary-expression before token errors

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: