I am trying to enumerate all remote desktop sessions in C# using the function WtsEnumerateSessionsExA
defined in WtsApi32.dll
.
This function writes into an array of WTS_SESSION_INFO_1A
structs whose pointer is passed as a parameter. You can find the documentation here:
I have implemented the WTS_SESSION_INFO_1A
struct and WTS_CONNECT_STATE_CLASS
in C# like this:
struct WtsSessionInfoClass
{
uint ExecEnvId;
WtsConnectStateClass state;
uint sessionId;
string pSessionName;
string pHostName;
string pUserName;
string pDomainName;
string pFarmName;
}
enum WtsConnectStateClass
{
WTSActive,
WTSConnected,
WTSConnectQuery,
WTSShadow,
WTSDisconnected,
WTSIdle,
WTSListen,
WTSReset,
WTSDown,
WTSInit
}
I have imported the required functions in a class called Native32
:
[DllImport("WtsApi32.dll")]
internal static extern IntPtr WTSOpenServerEx(string name);
[DllImport("WtsApi32.dll")]
internal static extern bool WTSEnumerateSessionsExA(
IntPtr hServer,
UIntPtr pLevel,
uint Filter,
out WtsSessionInfoClass[] ppSessionInfo,
UIntPtr pCount
);
Finally my implementation is the following:
UIntPtr len = new UIntPtr();
WtsSessionInfoClass[] sessions;
IntPtr handle = Native32.WTSOpenServerEx("MyMachineName"); // This function gets the server handle and works fine
Native32.WTSEnumerateSessionsExA(handle, new UIntPtr(1), 0, out sessions, len); // This function will produce AccessViolationException
...
When executing the code, the call to Native32.WTSEnumerateSessionsExA
fails due to AccessViolationException
.
What am I doing wrong here? Any help is appreciated.