Search code examples
c#winapiterminal-services

Using WTSQuerySessionInformation in Visual C#


I am trying to use the function WTSQuerySessionInformation in a Visual C# project, including the following lines in the class definition:

[DllImport("Wtsapi32.dll")]
        static extern bool WTSQuerySessionInformation(
            System.IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned); private Boolean remote_connected = false;

I get an error saying:

Error: he type or namespace name 'WTS_INFO_CLASS' could not be found (are you missing a using directive or an assembly reference?)

Can anyone please let me know what needs to be done in the project to fix this error?


Solution

  • You are nearly there:

    enum WTS_INFO_CLASS
    {
         WTSInitialProgram,
         WTSApplicationName,
         WTSWorkingDirectory,
         WTSOEMId,
         WTSSessionId,
         WTSUserName,
         WTSWinStationName,
         WTSDomainName,
         WTSConnectState,
         WTSClientBuildNumber,
         WTSClientName,
         WTSClientDirectory,
         WTSClientProductId,
         WTSClientHardwareId,
         WTSClientAddress,
         WTSClientDisplay,
         WTSClientProtocolType,
         WTSIdleTime,
         WTSLogonTime,
         WTSIncomingBytes,
         WTSOutgoingBytes,
         WTSIncomingFrames,
         WTSOutgoingFrames,
         WTSClientInfo,
         WTSSessionInfo
    };
    
    [DllImport("Wtsapi32.dll", SetLastError=true)]
    static extern bool WTSQuerySessionInformation(
        IntPtr hServer, 
        uint sessionId, 
        WTS_INFO_CLASS wtsInfoClass, 
        out IntPtr ppBuffer, 
        out uint pBytesReturned
    );
    

    Note that sessionId is a DWORD which is an untyped 32 bit integer.