问题
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