Shut Down, Restart, and Log Off From Code


I was recently asked how do you shut the system down from VB.NET, the answer is to a make a few calls to the Win32 API to do this.

First you need to set up a few constants that we will need when we call the Win32 API.

‘ Constants
Const SE_PRIVILEGE_ENABLED As Integer = &H2
Const TOKEN_QUERY As Integer = &H8
Const TOKEN_ADJUST_PRIVILEGES As Integer = &H20
Const SE_SHUTDOWN_NAME As String = “SeShutdownPrivilege”
‘ Exit Windows Constants
Const EWX_LOGOFF As Integer = &H0
Const EWX_SHUTDOWN As Integer = &H1
Const EWX_REBOOT As Integer = &H2
Const EWX_FORCE As Integer = &H4
Const EWX_POWEROFF As Integer = &H8
Const EWX_FORCEIFHUNG As Integer = &H10
‘Structure
<StructLayout(LayoutKind.Sequential, Pack:=1)> _
Friend Structure Luid
   Public Count As Integer
   Public Luid As Long
   Public Attr As Integer
End Structure ‘TokPriv1Luid

After we set up our constants we need to define our API calls for the functions we are going to use.

‘ Get Current Processes.  Click here for the API docs for this function.
<DllImport(“kernel32.dll”, ExactSpelling:=True)> _
Function GetCurrentProcess() As IntPtr
End Function

‘ Open Process Token.  Click here for the API docs for this function.
<DllImport(“advapi32.dll”, SetLastError:=True)> _
Function OpenProcessToken(ByVal h As IntPtr, ByVal acc As Integer, ByRef phtok As IntPtr) As Boolean
End Function

‘ Look up Priviledge Value.  Click here for the API docs for this function.
<DllImport(“advapi32.dll”, SetLastError:=True)> _
Friend Function LookupPrivilegeValue(ByVal host As String, ByVal name As String, ByRef pluid As Long) As Boolean
End Function

‘ Adjust Token Priviledges.  Click here for the API docs for this function.
<DllImport(“advapi32.dll”, ExactSpelling:=True, SetLastError:=True)> _
Friend Function AdjustTokenPrivileges(ByVal htok As IntPtr, ByVal disall As Boolean, ByRef newst As Luid, ByVal len As Integer, ByVal prev As IntPtr, ByVal relen As IntPtr) As Boolean
End Function

‘ Exit Windows  Click here for the API docs for this function.
<DllImport(“user32.dll”, ExactSpelling:=True, SetLastError:=True)> _
Friend Function ExitWindowsEx(ByVal flg As Integer, ByVal rea As Integer) As Boolean
End Function

Now that we have done the housekeeping that is needed to make the needed API calls we can write the Shutdown function.

‘ Exit Windows Sub
Private Sub DoExitWindows(ByVal flg As Integer)
  Dim tp As Luid
  Dim hproc As IntPtr = GetCurrentProcess()
  Dim htok As IntPtr = IntPtr.Zero

  ‘Get a token for this process. 
  OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, htok)
  tp.Count = 1
  tp.Luid = 0
  tp.Attr = SE_PRIVILEGE_ENABLED

  ‘Get the LUID for the shutdown privilege.
   LookupPrivilegeValue(Nothing, SE_SHUTDOWN_NAME, tp.Luid)

   ‘Get the shutdown privilege for this process.
   AdjustTokenPrivileges(htok, False, tp, 0, IntPtr.Zero, IntPtr.Zero)

  ‘Exit Windows
  ExitWindowsEx(flg, 0)
End Sub

With the function written we can call it with our various constants to determine how it acts.  The three most common methods are listed below.

‘ Shutdown
DoExitWindows(EWX_SHUTDOWN)

‘ Restart
DoExitWindows(EWX_REBOOT Or EWX_FORCE)

‘ Log off
DoExitWindows(EWX_LOGOFF)


Comments (19)

  1. Bill Vaughn says:

    I have a far (far) faster way to shut down the computer. Try to setup a port with the HP TCP/IP interface. It restarts the system every time without fail… 😉 I expect it’s a bit hard on the OS though–something like stopping a jet engine by tossing a 4×4 timber into the air intake.

  2. raghav says:

    Thank you very much for giving information

    about shutdown.

    One more Q:

    how to lock complete keyboard using vb6 code?

    i am using XP.

    Please mail me.

    thanking you

    raghavendra kulkarni

    raghav_cse@rediffmail.com

  3. raghav says:

    Thank you very much for giving information

    about shutdown.

    One more Q:

    how to lock complete keyboard using vb6 code?

    i am using XP.

    Please mail me.

    thanking you

    raghavendra kulkarni

    raghav_cse@rediffmail.com

  4. Bain says:

    Thanx much for the code

    IS THERE ANY WAY I CAN IMPLEMENT THIS IS C LANGUAGE OR JAVA PLEASE

    HELP

    YOU CONTACT ME happydaysgood@yahoo.com

  5. Shekhar says:

    How can I get more code of VB 6.0

  6. S.Withanage says:

    I am trying to learn visual basic language. But I couldn’t find out some kind of question. pls. help me.

  7. Withanage says:

    I am trying to learn visual basic language. But I couldn’t find out some kind of question. pls. help me.

    Pls. Contact me following

    sdti93@hotmail.com

  8. Philip says:

    A good start to Visual basic you must know the enviroment and familirize the following reserve words loops, statement and etc. and have wide thinking.

    How to put MSFlexgrid column header and display data fined to it from database?

  9. Philip says:

    A good start to Visual basic you must know the language enviroment and familirize the following reserve words loops, statement and etc. and have wide thinking.

    How to put MSFlexgrid column header and display data fined from database?

  10. 송다솔 says:

  11. Peter Monadjemi says:

    Wouldn’t it be much easier to use WMI to shutdown any workstation in the network? Its just a few lines of code (if you use the WMI Scripting Lib the same for VB and VB.NET) and no API calls at all.

    Peter

    PS: For all those people asking questions about VB6: a newsgroup like microsoft.public.vb.general.discussion on msnews.microsoft.com would be a much better place

  12. Crouchie1998 says:

    I done this around a year ago (25/ Jan/2004). You can find my user sample here:

    http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=6d5ba0f2-77c8-43ce-a0ec-4a9a89d47fad

  13. Brad McCabe says:

    I went back and forth on doing this via the APIs and showing it done with WMI. I settled on the APIs first as I figured WMI was less well know and its use less wide spread.

    WMI is a much cleaner solution and allows for more "Features" like shuting down remote computer. In the end there are multiple ways to do this as you point out.

  14. Cool but can I do this in visual basic.net???

  15. yapchoonmin@gmail.com says:

    I am using Visual Basic 6.0 and Win ME . How do I do it ?

    Your help is greatly appreciated

  16. Brad McCabe says:

    See http://www.developer.be/index.cfm/fuseaction/tutorialDetail/GroupID/35.htm for inforamation about calling Win32 APIs from VB 6.0. As luck would have it this article is about shutting down the system also.

  17. Derek Schwartz says:

    I found a realy slick way to KILL Windows XP from VB.NET. In fact, it’s the only way I know of to reliably force an instant BSOD! I was messing around with WMI and, for testing purposes, I had it recurse through the list of currently running processes. Somehow, without thinking, I added the kill command inside the loop and it killed XP faster than I’ve ever seen! DUH! 🙂