3

I need to implement a dead man's switch in my application. If the application is running from RDP, I need to act if it loses connection to the remote client.

I know when I am running in RDP by using

GetSystemMetrics(SystemMetric.SM_REMOTESESSION)

But when the client closes without signing out, the session will continue. This is the scenario I want to react to, but I don't know how to detect a client disconnecting. I need to know if there is an active RDP user or not.

I could potentially find the remote endpoint by watching the RDP port, but as think could potentially be setup on a non-default port, I'd like to avoid this solution if a better one exists.

I'd prefer a solution that was not specific to WinForms, WPF, UWP etc. Bonus points if it works with .NET Core as well.

Troels Larsen
  • 4,462
  • 2
  • 34
  • 54
  • maybe [this](https://stackoverflow.com/questions/13987213/c-sharp-get-rdc-rdp-and-console-session-information) help. – BWA Nov 08 '18 at 08:39
  • 2
    Note the SM_REMOTESESSION is not always recommended: https://learn.microsoft.com/en-us/windows/desktop/termserv/detecting-the-terminal-services-environment – Simon Mourier Nov 08 '18 at 08:49

2 Answers2

1
  1. Yes you can do it using PS e.g. using > query user /server:$SERVER
  2. Any PS command you can call from .Net.

Regards Ren

0

Not a .NET Core solution, but a windows API one. There are session change notifications that you can opt into via WTSRegisterSessionNotification (and similarly unregister later).

These notifications are then delivered in your windows message loop, so you need to be running one. (WinForms and WPF do, and there are specific mechanisms to allow you to perform custom message handling)

You'll then get notified when the session becomes locked or disconnected.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • Unfortunately, WTSRegisterSessionNotification requires the ability to override WndProc, and I'm in a console application. I was hoping there was a better solution for this, as think should shutdown a service. – Troels Larsen Nov 08 '18 at 09:00