Chapter 73. How to Programmatically Log Off or Reboot the Machine

Logging off logically means ending your logon session (Item 17), which means closing any processes that have tokens (Item 16) that point to your logon session. Win32 provides a function to do this called ExitWindowsEx. It looks at the logon session of the code that called it and then closes all processes running within that session. If the interactive user is being logged off, the Winlogon desktop will become active afterward. The C# code for this is shown in Figure 73.1.

Example 73.1. Forcing a logoff programmatically

 using System.Runtime.InteropServices; class LogOff { static void Main() { ExitWindowsEx(0, 0); } [DllImport("user32.dll")] static extern bool ExitWindowsEx(uint flags, ...

Get The .NET Developer's Guide to Windows Security 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.