Force a Windows Shutdown or Logoff

Problem

You want to log off or shut down Windows programmatically.

Solution

Use the unmanaged ExitWindowsEx API function.

Discussion

The .NET Framework doesn’t include the functionality needed to shut down or restart Windows. However, you can easily do so using the ExitWindowsEx function from the user32.dll library. This function accepts a parameter that indicates whether you want a logoff (value 0), a restart (value 2), or a shutdown (value 1). In addition, you can add a force constant (value 4) to force the system to take the indicated action even if the user attempts to cancel it. This drastic step is usually resented by users and should be used with caution.

The following Console application imports the ExitWindowsEx ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.