views:

848

answers:

3

Is there a way my program can determine when it's running on a Remote Desktop (Terminal Services)?

I'd like to enable an "inactivity timeout" on the program when it's running on a Remote Desktop session. Since users are notorious for leaving Remote Desktop sessions open, I want my program to terminate after a specified period of inactivity. But, I don't want the inactivity timeout enabled for non-RD users.

+11  A: 

GetSystemMetrics(SM_REMOTESESSION) (as described in http://msdn.microsoft.com/en-us/library/aa380798.aspx)

Franci Penov
+5  A: 

Here's the C# managed code i use:

/// <summary>
/// Indicates if we're running in a remote desktop session.
/// If we are, then you MUST disable animations and double buffering i.e. Pay your taxes!
/// 
/// </summary>
/// <returns></returns>
public static Boolean IsRemoteSession
{
    //This is just a friendly wrapper around the built-in way
    get
    {
     return System.Windows.Forms.SystemInformation.TerminalServerSession;
    }
}
Ian Boyd
+1  A: 

The following works if you want to know about YOUR application which is running in YOUR session:

BOOL IsRemoteSession(void)
{
   return GetSystemMetrics( SM_REMOTESESSION );
}

But not in general for any process ID.


If you want to know about any arbitrary process which could be running in any arbitrary session then you can use the below method.

You can first convert the process ID to a session ID by calling ProcessIdToSessionId. Once you have the session ID you can use it to call: WTSQuerySessionInformation. You can specify WTSInfoClass as value WTSIsRemoteSession and this will give you the information about if that application is a remote desktop connection or not.

BOOL IsRemoteSession(DWORD sessionID)
{
   //In case WTSIsRemoteSession is not defined for you it is value 29
   return WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, sessionID, WTSIsRemoteSession, NULL, NULL);
}
Brian R. Bondy
What are the situations that can cause a process to be in a different session? Is this if i'm asking about services, or processing running under other logged in users?
Ian Boyd
When you do a new login, either from the local machine or via RDP without the /console switch, a new session is created. When a new session is created any process created will be started in that session by default. You can also target sessions when you create a process via Win32 API CreateProcessAsUser.
Brian R. Bondy