Log off a Windows user locally using c#

Use the WTSDisconnectSession() Windows API. See article here.

using System;
using System.Runtime.InteropServices;
using System.ComponentModel;

class Program
{
  [DllImport("wtsapi32.dll", SetLastError = true)]
  static extern bool WTSDisconnectSession(IntPtr hServer, int sessionId, bool bWait);

  [DllImport("Kernel32.dll", SetLastError = true)]         
  static extern WTSGetActiveConsoleSessionId();

  const int WTS_CURRENT_SESSION = -1;
  static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;

  static void Main(string[] args)
  {
    if (!WTSDisconnectSession(WTS_CURRENT_SERVER_HANDLE,
         WTS_CURRENT_SESSION, false))
      throw new Win32Exception();
  }
}

Even without remote desktop, it will disconnect the current user and go to the login screen. The processes will still run in the background. After manually login in again, the running programs will appear as they were before the disconnect.


  [DllImport("wtsapi32.dll", SetLastError = true)]
  static extern bool WTSDisconnectSession(IntPtr hServer, int sessionId, bool bWait);


When you use WTSDisconnectSession in remote desktop is equivalent to 'Close' the remote desktop windows. It is disconnect your Windows session, but hold the connection.

The advantage is you can reconnect back the session later by remote log in again.
The disadvantage is the Windows may not be able log in by other user when the remote desktop connection is full.


To simulate Windows 'Log off' should use ExitWindowsEx under user32.dll

[DllImport("user32.dll", SetLastError = true)]
static extern bool ExitWindowsEx(uint uFlags, uint dwReason);

public static bool WindowsLogOff() {
  return ExitWindowsEx(0, 0);
}

if you want to Force the user to log off you need to add the EWX_FORCE flag like this:

ExitWindowsEx(0 | 0x00000004, 0);

More details on the function here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa376868(v=vs.85).aspx


piggybacking off Leng Weh Seng's answer (since I can't comment), if you want to Force the user to log off you need to add the EWX_FORCE flag like this:

ExitWindowsEx(0 | 0x00000004, 0);

More details on the function here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa376868(v=vs.85).aspx