Shut down system

Sample code of shut down system from service context:

DWORD ShutdownSystem()
{
    OSVERSIONINFO osversion = {0};
    osversion.dwOSVersionInfoSize = sizeof(osversion);
    GetVersionEx(&osversion);

    // check how many users logged on
    DWORD dwConnectedSessions = 0;
    HANDLE hserver = WTSOpenServer(NULL);
    if(NULL != hserver)
    {
        PWTS_SESSION_INFO pserverinfo = NULL;
        DWORD dwSessionCount = 0;

        // WTSEnumerateSessions will fail with error 1151 on win2k, we don’t care
        if(WTSEnumerateSessions(hserver, 0, 1, &pserverinfo, &dwSessionCount))
        {
            for(DWORD dwSessionIndex = 0; dwSessionIndex = 6) && (0 == pserverinfo[dwSessionIndex].SessionId))
                    continue;

                if(WTSActive == pserverinfo[dwSessionIndex].State || WTSDisconnected == pserverinfo[dwSessionIndex].State)
                    ++dwConnectedSessions;
            }

            if(NULL != pserverinfo)
                WTSFreeMemory(pserverinfo);
        }

        WTSCloseServer(hserver);
        hserver = NULL;
    }

    //shutdown system
   HANDLE hToken = 0;
   DWORD dwError = 0;

   // Get token of current thread.
   if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, TRUE, &hToken))
   {
       dwError = GetLastError();
       return dwError;
   }

   TOKEN_PRIVILEGES tkp;
   memset(&tkp, 0, sizeof(tkp));
   tkp.PrivilegeCount = 1;  // one privilege to set   
   tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
   LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

   AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
   dwError = GetLastError();
   ::CloseHandle(hToken);
   _ASSERT(dwError == ERROR_SUCCESS)

   dwError = ERROR_SUCCESS;
   // Shut down the system normally without forcing application to terminate.
   if(dwConnectedSessions > 1 || osversion.dwMajorVersion < 6)
   {
       if (!ExitWindowsEx(EWX_POWEROFF,
           SHTDN_REASON_MAJOR_APPLICATION |
           SHTDN_REASON_MINOR_MAINTENANCE))
       {
            dwError= GetLastError();
       }
   }
   else
   {
       if(!InitiateSystemShutdown(NULL, NULL, 0, FALSE, FALSE))
            dwError= GetLastError();
   }
   return dwError;
} 
Advertisements

Posted on September 9, 2009, in Uncategorized. Bookmark the permalink. Leave a comment.

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: