O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required