How to detect RDC from C#.net [duplicate]

ε祈祈猫儿з 提交于 2019-12-11 17:45:14

问题


Possible Duplicate:
How do you retrieve a list of logged-in/connected users in .NET?

I have hosted WCF service in IIS on a machine. Now i want to write a method in the service by which I could detect whether the hosted machine is currently being used by any Remote Desktop Connection or not.

Is there any other better way to find out this, and what are the exact code APIs by which RDC connection is detected.

I am using C#.net, framework 3.5


回答1:


There are two options for you. You can use the P/Invoke Calls to the WSTAPI library however it is easy to mess stuff up and get resource leaks.

Your other option is to use the WTSAPI wrapper library Cassia. I have used that before and it is easy to use and the classes are fairly self documenting.

In Cassia your function would simply be

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;
}

I did not test the above, and I think "active" is used if you are a console session where "Connected" is for RDP sessions. there are lot more states, look at the enum for all of the options.




回答2:


RDP servers listen on port 3389 by default (but can be configured differently).

Therefore (even not being 100% reliable) this can be used to check any active RDP connections.

bool inUse = IPGlobalProperties.GetIPGlobalProperties()
              .GetActiveTcpConnections()
              .Any(tcp => tcp.LocalEndPoint.Port == 3389);

EDIT

I added @t3hn00b's suggestion.

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);
    }
}

namespace: System.Net.NetworkInformation



来源:https://stackoverflow.com/questions/13619459/how-to-detect-rdc-from-c-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!