In our previous post, “Logging Off A Windows PC In C# & .NET”, we looked at how to log off a Windows PC using C#, invoking the Windows API.

In this post, we will look at how to achieve the same using Visual Basic .NET.

The code is pretty much identical.

First, using the DllImport attribute, we import the relevant function call.

Imports System.Runtime.InteropServices

<DllImport("user32.dll", SetLastError:=True)>

Public Shared Function ExitWindowsEx(uFlags As UInteger, dwReason As UInteger) As Boolean
  
End Function

Invoking it is as simple as this:

Dim success As Boolean = ExitWindowsEx(0, 0)

If Not success Then
    Console.WriteLine($"Error: {Marshal.GetLastWin32Error()}")
End If

It is poor practice to have magic numbers like this, so it is probably better to create some constants.

Const EWX_LOGOFF As UInteger = &H0

Our method call thus becomes:

Dim success As Boolean = ExitWindowsEx(EWX_REBOOT, 0)

Of interest here is that the &H prefix means that the following value is in hexadecimal

Happy hacking!