Detect Active RDP Session

Viewed 1767

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.

1 Answers

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.

Related