About   -   Contact   -   Purchase   -   Search   -   What's New

Force Windows to Restart from within VB
The following code will cause Windows to be restarted. In order to test this example, create a new VB project consisting of only one form. Add to the form a single command button (cmdRestart) with a caption like 'Restart Windows'. Then place the following API declaration into the form's declarations section:
Option Explicit
'Determine 16-bit or 32-bit platform
#If Win32 Then
	Private Declare Function ShutdownWindows Lib "user32" Alias _
	  "ExitWindowsEx" (ByVal uFlags As Long, _
	  ByVal dwReserved As Long) As Long
	Private Declare Function ShutdownWindows Lib "user" Alias _
	  "ExitWindows" (ByVal wReturnCode As Integer, _
	  ByVal dwReserved As Integer) As Integer
#End If
Private Const EWX_LOGOFF = 0
Private Const EWX_SHUTDOWN = 1
Private Const EWX_REBOOT = 2
Private Const EWX_FORCE = 4

This technique works in Win 3.x, Windows 95/98, and Windows NT. Now add code behind the command button's click event to prompt the user for confirmation before executing - as follows:

Sub cmdRestart_Click ()
'<DESC>		Routine to Shutdown/Restart Windows 
'		directory</DESC>
'<RETURN>	Long: determines whether windows
'		shutdown successfully
'<ACCESS>	Public
'<ARGS>		Integer: Shutdown Mode
'				</ARGS>
'<USAGE>	x = ShutdownWindows(EWX_REBOOT, 0)
'				</USAGE>
    Dim x As Integer
    Dim Response As Variant
    Response = MsgBox("This routine will Restart Windows!" &  _
      vbCrLf & "Are you sure you want to do this?", vbYesNo + vbQuestion, _
      "Restart Windows?")
    If Response = vbYes Then
    'Cause Windows to Restart
    'If any programs refuse to terminate, this function will return ZERO
        x = ShutdownWindows(EWX_REBOOT, 0)
        If Not x Then
            Response = MsgBox("Some program(s) refused to terminate",  _
	      vbExclamation, "Cannot Restart Windows")
        End If
    End If

End Sub

Finally, before running the code, remember to save your project - Undo seems to have little effect once Windows has restarted…


Top of Page

Legal Notice

Ken Howe 2011