Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

ReBoot system

Posted on 2000-03-23
6
410 Views
Last Modified: 2013-12-03
Is there an API call or calls that I can use to shutdown windows 95/98 and or NT, and reboot the PC.   I want to do a controlled shutdown and reboot from a C++ program.
If not an API call any way to do the a controlled reboot.
0
Comment
Question by:larryH
6 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 2650910
Simply use

ExitWindowsEx ( EXW_REBOOT, 0);

Feel free to ask if you need more information!

0
 

Author Comment

by:larryH
ID: 2654874
If it were only that simple...
      Tried using the ExitWindowsEx API call, and got an error code of 1314, which is ERROR_PRIVILEGE_NOT_HELD.  Sounds like an authorization problem.  After doing some research, I also tried using LogonUser and ImpersonateLoggedOnUser, both of which returned errors 1314, ERROR_PRIVILEGE_NOT_HELD.  Found a similar problem on Microsoft's support site, and followed the instructions there to change logon privileges for myself, going into User Manager/User Rights Policy and granting myself the privilege "Act as part of the operating system".  After doing this, the Logon User and ImpersonateLoggedOnUser now return error code 1056, which is ERROR_SERVICE_ALREADY_RUNNING, and ExitWindowsEx still returns 1314.  Don't know what else to try.  Help
0
 
LVL 1

Expert Comment

by:castorix
ID: 2654920
You must adjust token privileges under NT before calling ExitWindowsEx()
Something like this =>

HANDLE hToken;
TOKEN_PRIVILEGES NewPriv;
LUID  Luid;
OSVERSIONINFO  VersionInformation;
 ...
 //Test version
 GetVersionEx(&VersionInformation);
 if (VersionInformation.dwPlatformId==VER_PLATFORM_WIN32_NT) {
 // SE_SHUTDOWN_NAME privilege
   if (!OpenProcessToken(GetCurrentProcess(),
 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,&hToken))
   error("OpenProcessToken");
           LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,&Luid);   NewPriv.PrivilegeCount=1;
   NewPriv.Privileges[0].Luid=Luid;
   NewPriv.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
   AdjustTokenPrivileges(hToken,FALSE,&NewPriv,0,
       (PTOKEN_PRIVILEGES)NULL,0);
   if (GetLastError() !=ERROR_SUCCESS)
       error("AdjustTokenPrivileges");
   }
0
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 
LVL 2

Accepted Solution

by:
DarrinE earned 100 total points
ID: 2655372
The follwing code is a complete snippet (including the support functions) to shutdown windows no matter what the platform

You call the function as :

ShutDowWindows(6); // force windows to reboot





/***********************************************************************
Function      :            ShutDownWindows
Params            :            iType =

                                    · 0 - LOGOFF      - Shuts down all running processes, then logs the user off.

                                    · 1 - SHUTDOWN      - Shuts down the system to a point at which it is safe to turn off the power. All file buffers have been flushed to disk, and all running processes have stopped.

                                    · 2 - REBOOT      - Shuts down the system and then restarts the system.

                                    · 4 - FORCE            - Forces processes to terminate. When this flag is set, Windows does not query running applications to inform them that Windows is shutting down. This can cause the applications to lose data, therefore, you should only use this flag in an emergency.

                                    · 8 - POWEROFF      - Shuts down the system and turns off the power. The system must support the power-off feature.

  there is no
  return value
***********************************************************************/
void ShutDownWindows(int itype)
{
      // Start the display properties dialog
      STARTUPINFO si;
      PROCESS_INFORMATION pi;
      char szCmdString[80];
    DWORD pdwMajor = 0;
      DWORD pdwMinor = 0;
    HRESULT hResult;

//version of shell required for the following code
//4.72.3612.1700

//version of internet explorer 5
// 5.00.2614.3500
  /* Set the size of the buffer */

    hResult = GetShell32Version(&pdwMajor,&pdwMinor);

#ifdef _DEBUGGING  
    if (hResult != E_FAIL)
         {
            if(hResult != E_INVALIDARG)
            {
               char msgString[100];
               wsprintf(msgString, "Major %ld Minor %ld", pdwMajor, pdwMinor);
               MessageBox(NULL, msgString, "Shell Version", MB_OK);
            }
            else
              MessageBox(NULL, "E_INVALIDARG", "Error", MB_OK);
         }
    else
        MessageBox(NULL, "E_FAIL", "Error", MB_OK);
#endif

      if(!IsWNT())
      {
            if ((pdwMajor >= 4) && (pdwMinor >=71))
            {
                  ZeroMemory( &si, sizeof(si) );
                  si.cb = sizeof(si);

                  wsprintf(szCmdString, "rundll32.exe shell32.dll,SHExitWindowsEx %i,,", itype);

                  CreateProcess( NULL,      // No module name (use command line).
                        szCmdString,            // Command line.
                        NULL,                        // Process handle not inheritable.
                        NULL,                        // Thread handle not inheritable.
                        FALSE,                        // Set handle inheritance to FALSE.
                        0,                              // No creation flags.
                        NULL,                        // Use parent’s environment block.
                        NULL,                        // Use parent’s starting directory.
                        &si,                        // Pointer to STARTUPINFO structure.
                        &pi);                        // Pointer to PROCESS_INFORMATION structure.

            }
            else
            {
             ShutDownWin((UINT)itype);
            }
      }
      else
      {
       ShutDownNT((UINT) itype);
      }

      return;
}
/*

#define EWX_LOGOFF           0
#define EWX_SHUTDOWN         0x00000001
#define EWX_REBOOT           0x00000002
#define EWX_FORCE            0x00000004
#define EWX_POWEROFF         0x00000008
#if(_WIN32_WINNT >= 0x0500)
#define EWX_FORCEIFHUNG      0x00000010
#endif /* _WIN32_WINNT >= 0x0500

*/



   //
   // EnumWindowsProc must be called from a Windows
   // application on Windows 95.
   //
void ShutDownWin(UINT itype)
{

 if(!IsWNT())
 {
   // If the shell version is not larger than 4.71
   // then we
   // Close all open applications.
   //
   EnumWindows((WNDENUMPROC)EnumWindowsProc, 0);

   // Now do a regular logoff.
   ExitWindowsEx(itype , 0);
 }
 else
 {
       ShutDownNT(itype);
 }

 return;

}



void ShutDownNT(UINT uFlags)
{
      HANDLE hToken;
      TOKEN_PRIVILEGES tkp;
 
      // Get a token for this process.
      if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
    //error("OpenProcessToken");
 
      // 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);
 
      // Cannot test the return value of AdjustTokenPrivileges.
       if (GetLastError() != ERROR_SUCCESS)
//            error("AdjustTokenPrivileges");
 
      // Shut down the system and force all applications to close.
 
      if (!ExitWindowsEx(uFlags, 0))
//            error("ExitWindowsEx");

    return;
}


BOOL CALLBACK EnumWindowsProc(HWND hwnd, DWORD lParam)
{
       DWORD      pid = 0;
       LRESULT    lResult;
       HANDLE     hProcess;
       DWORD      dwResult;

       lResult = SendMessageTimeout(
                                                  hwnd,
                                                WM_QUERYENDSESSION,
                                                  0,
                                                      ENDSESSION_LOGOFF,
                                                      SMTO_ABORTIFHUNG,
                                                      2000,
                                                      &dwResult);

       if( lResult )
       {
          //
          // Application will terminate nicely, so let it.
          //
          lResult = SendMessageTimeout(
                                                            hwnd,
                                                            WM_ENDSESSION,
                                                            TRUE,
                                                            ENDSESSION_LOGOFF,
                                                            SMTO_ABORTIFHUNG,
                                                            2000,
                                                            &dwResult);

       }
       else  // You have to take more forceful measures.
       {
           //
           // Get the ProcessId for this window.
           //
           GetWindowThreadProcessId(hwnd, &pid );
           //
           // Open the process with all access.
           //
           hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
           //
           // Terminate the process.
           //
           TerminateProcess(hProcess, 0);

       }
       //
       // Continue the enumeration.
       //
       return TRUE;
}

/*********************************************************************************************************************
Version Platform
4.00 Windows 95, Windows NT 4.0, Internet Explorer 3.0, and Internet Explorer 4.0 without Web Integrated Desktop.
4.71 Internet Explorer 4.0 with Web Integrated Desktop.
4.72 Internet Explorer 4.01 with Web Integrated Desktop.
**********************************************************************************************************************/
HRESULT GetShell32Version(LPDWORD pdwMajor, LPDWORD pdwMinor)
{
 HINSTANCE   hShell32;

  if(   IsBadWritePtr(pdwMajor, sizeof(DWORD)) ||
        IsBadWritePtr(pdwMinor, sizeof(DWORD)))
     return E_INVALIDARG;

      *pdwMajor = 0;
      *pdwMinor = 0;

      //Load the DLL.
      hShell32 = LoadLibrary(TEXT("shell32.dll"));

      if(hShell32)
         {
         HRESULT           hr = S_OK;
         DLLGETVERSIONPROC pDllGetVersion;
   
         /*
         You must get this function explicitly because earlier versions of the DLL
         don't implement this function. That makes the lack of implementation of the
         function a version marker in itself.
         */
         pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hShell32, TEXT("DllGetVersion"));
   
         if(pDllGetVersion)
              {
              DLLVERSIONINFO    dvi;
     
              ZeroMemory(&dvi, sizeof(dvi));
              dvi.cbSize = sizeof(dvi);
   
              hr = (*pDllGetVersion)(&dvi);
     
              if(SUCCEEDED(hr))
                   {
                   *pdwMajor = dvi.dwMajorVersion;

                   *pdwMinor = dvi.dwMinorVersion;
                   }
              }
         else
              {
              /*
              If GetProcAddress failed, the DLL is a version previous to the one
              shipped with IE 3.x.
              */
              *pdwMajor = 4;
              *pdwMinor = 0;
              }
   
         FreeLibrary(hShell32);

         return hr;
         }

  return E_FAIL;
}

__declspec( dllexport ) BOOL WINAPI IsWNT(void)
{
   OSVERSIONINFO v;
   v.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
   GetVersionEx(&v);
   return (v.dwPlatformId==VER_PLATFORM_WIN32_NT);
}


If you need anything more ask

DarrinE
0
 
LVL 86

Expert Comment

by:jkr
ID: 2655590
>>If it were only that simple...

It is that simple - the docs state that this privilege *is* needed on NT...

It doesn't only have to be enabled, the user calling this API must also be granted this privilege. Thus, DarrinE's code will only work for members of the administrators group.

BTW: On NT, you might also want to use 'InitiateSystemShutdown()'
0
 

Author Comment

by:larryH
ID: 2674181
Thanks it works just great.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
VS2015 compilation and missing DLLs 9 162
Changing the installation path of this MSI 5 107
Explain Unit of Work pattern 2 69
VIDEO DATASOURCE Control Resize issue 2 30
In this article, I will show how to use the Ribbon IDs Tool Window to assign the built-in Office icons to a ribbon button.  This tool will help us to find the OfficeImageId that corresponds to our desired built-in Office icon. The tool is part of…
For a while now I'v been searching for a circular progress control, much like the one you get when first starting your Silverlight application. I found a couple that were written in WPF and there were a few written in Silverlight, but all appeared o…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question