Welcome to MSDN Blogs Sign in | Join | Help
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)

Published Wednesday, March 02, 2005 6:20 AM by Brad_McCabe

Comments

# Locking the Computer from Code @ Wednesday, March 02, 2005 9:25 AM

Brad McCabe's WebLog

# re: Shut Down, Restart, and Log Off From Code @ Wednesday, March 02, 2005 2:15 PM

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 4x4 timber into the air intake.

Bill Vaughn

# re: Shut Down, Restart, and Log Off From Code @ Thursday, March 03, 2005 12:19 AM

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

raghav

# re: Shut Down, Restart, and Log Off From Code @ Thursday, March 03, 2005 12:23 AM

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

raghav

# re: Shut Down, Restart, and Log Off From Code @ Thursday, March 03, 2005 1:03 AM

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

Bain

# re: Shut Down, Restart, and Log Off From Code @ Thursday, March 03, 2005 4:08 AM

How can I get more code of VB 6.0

Shekhar

# How to refresh data Grid for display the latest record from table @ Thursday, March 03, 2005 6:35 AM

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

S.Withanage

# How to refresh data grid for display the latest record from table @ Thursday, March 03, 2005 6:48 AM

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

Withanage

# re: Shut Down, Restart, and Log Off From Code @ Friday, March 04, 2005 12:13 AM

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?

Philip

# re: Shut Down, Restart, and Log Off From Code @ Friday, March 04, 2005 12:16 AM

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?

Philip

# re: Shut Down, Restart, and Log Off From Code @ Sunday, March 06, 2005 12:07 AM

송다솔

# re: Shut Down, Restart, and Log Off From Code @ Sunday, March 06, 2005 8:26 AM

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

Peter Monadjemi

# re: Shut Down, Restart, and Log Off From Code @ Sunday, March 06, 2005 2:46 PM

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

Crouchie1998

# re: Shut Down, Restart, and Log Off From Code @ Tuesday, March 08, 2005 8:13 AM

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.

Brad McCabe

# re: Shut Down, Restart, and Log Off From Code @ Wednesday, March 09, 2005 10:37 AM

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

Justin Breithaupt

# re: Shut Down, Restart, and Log Off From Code @ Thursday, March 10, 2005 8:07 AM

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

Your help is greatly appreciated

yapchoonmin@gmail.com

# re: Shut Down, Restart, and Log Off From Code @ Thursday, March 10, 2005 10:35 AM

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.

Brad McCabe

# re: Shut Down, Restart, and Log Off From Code @ Thursday, March 17, 2005 2:56 AM

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! :)

Derek Schwartz

# apagar el ordenador | hilpers @ Tuesday, January 20, 2009 2:13 PM

PingBack from http://www.hilpers-esp.com/493218-apagar-el-ordenador

apagar el ordenador | hilpers

New Comments to this post are disabled
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker