1

I have an program in production environment where I like to have a window to open, when a remote assistance are started on the pc, so the person connecting to the pc have some more options. But i can't find anything if this is possible? If so any idea how to detect it?

mortenstarck
  • 2,713
  • 8
  • 43
  • 76

1 Answers1

1

This can be done but I find it tricky and I generally avoid this. See How to detect RDC from C#.net for more info.

To start RDP listens on port 3389 so something like this should work.

int port = 3389;
using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp", false))
{
    if (key != null)
    {
        object value = key.GetValue("PortNumber");
        if (value != null) port = Convert.ToInt32(value);
    }
}

But the port number can be configured so this isn't the best way. Then there is Pinvoke and Cassia. with Cassia you could do something like:

public bool IsComputerUsedByTS()
{
    var tsMgr = new TerminalServicesManager();
    var localSvr = tsMgr.GetLocalServer();
    var sessions = localSvr.GetSessions();
    foreach(var session in sessions)
    {
        if(session.ConnectionState == ConnectionState.Active || 
           session.ConnectionState == ConnectionState.Connected) //Add more states you want to check for as needed
        {
            return true;
        }
    }
    return false;
}

And last but not least:

System.Windows.Forms.SystemInformation.TerminalServerSession

This uses a forms import but is a very simple solution. If you run your program in a remote desktop environment, this returns true.

Community
  • 1
  • 1
SilentStorm
  • 172
  • 1
  • 1
  • 12
  • Hi @SilentStorm I have just tried it and i it does not get an new session when RDC connection is open. – mortenstarck Nov 29 '16 at 12:35
  • You could also try this: `System.Windows.Forms.SystemInformation.TerminalServerSession` It returns a bool for rdp connections but uses a forms import. – SilentStorm Nov 29 '16 at 12:43
  • And what method did you use? the first or the latter? – SilentStorm Nov 29 '16 at 12:45
  • I have tried both, the first is only to get which port is being used by RDC. But the second, does not find the RDC connection, i finds the console and some seesion with some listing on, but not the right. – mortenstarck Nov 29 '16 at 14:27
  • Updated answer, test with that one-liner, I tested and this works. Didn't test the other ones, used them a while back and they worked for me. – SilentStorm Dec 02 '16 at 10:05