Home > Visual Basic > How to Log Off, Restart and Shutdown PC in Visual Basic

How to Log Off, Restart and Shutdown PC in Visual Basic

Here’s a small example of how to log off, restart and shutdown computer in Visual Basic. Open Visual Studio and create a new Windows Forms Application:

01

In the Solution Explorer right-click on ExitWindows –> Add –> Module… Leave the default name Module1.vb as is and click Add.

Paste the following code in Module1:

Public Declare Function ExitWindows Lib "user32" (ByVal uFlags As Long, _
ByVal dwReserved As Long) As Long

Public Const EWX_LOGOFF = 0
Public Const EWX_SHUTDOWN = 1
Public Const EWX_REBOOT = 2
Public Const EWX_FORCE = 4

Now, go to Form1.vb and add three buttons from the toolbox. Set the following properties for buttons:

Button1: Name:  btnLogOff

Text:    Log Off

Button2: Name:  btnReboot

Text:    Reboot

Button3: Name:  btnShutdown

Text:    Shutdown

Click F7 and paste the following code:

Public Class Form1
    Dim s As Long

    Private Sub btnLogOff_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnLogOff.Click
        ' Logoff current user
        s = ExitWindows(EWX_LOGOFF, 0&)
    End Sub

    Private Sub btnReboot_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnReboot.Click
        ' Reboot computer
        s = ExitWindows(EWX_REBOOT, 0&)
    End Sub

    Private Sub btnShutdown_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnShutdown.Click
        ' Shutdown computer
        s = ExitWindows(EWX_SHUTDOWN, 0&)
    End Sub
End Class

That’s it Smile. Download the solution from the link below.

Categories: Visual Basic Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Spam Protection by WP-SpamFree