Forcing a User to Logoff

Question: I am developing a Windows Form application and need to force the user to logout. I have been through the various namespaces of the .NET framework and don’t see anything that will help me. Any ideas?

Answer: You are correct that the .NET Framework doesn’t provide a way to do this. However, by importing the ExitWindowsEx function you can accomplish what you are looking to do. The following is a small code sample that should demonstrate this. The code is run from behind a button on a Windows Form.

Public Class Form1

Inherits System.Windows.Forms.Form

Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long

Private Enum ExitWindowsFlags

' logoff user without reboot

Logoff = 0

' Causes system shutdown

Shutdown = 1

' system reboot

Reboot = 2

' add this constant to prevent the user from cancelling

Forceit = 4

End Enum

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

ExitWindowsEx(ExitWindowsFlags.Logoff, 0&)

End Sub

End Class