2008-11-17 52 views

回答

20

假设你至少在.NET Framework 2.0上,不需要使用P/Invoke:只需检查System.Windows.Forms.SystemInformation.TerminalServerSessionMSDN)的值即可。

2

在user32.dll中使用GetSystemMetrics()函数。使用PInvoke来调用它。以下是第一个链接提供的示例代码。第二个链接告诉你如何在.NET中调用它。

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

完整代码:

[DllImport("User32.dll")] 
static extern Boolean IsRemoteSession() 
{ 
return GetSystemMetrics (SM_REMOTESESSION); 
} 

另外还有SystemInformation.TerminalServerSession属性,这决定了客户是否被连接到终端服务器会话。 MSDN的code provided是广泛的,所以我不会在这里复制它。

+1

请注意,`TerminalServerSession`只是对`GetSystemMetrics(SM_REMOTESESSION)`调用的包装。 – Cameron 2014-05-16 21:49:05

3

除了进行初始检查以查看您的桌面是否正在RDP会话中运行,您还可能需要处理远程会话在您的ap正在运行时连接或断开连接的情况。您可以在控制台会话中运行应用程序,然后有人可以启动到控制台的RDP连接。除非您的应用程序定期对GetSystemMetrics进行调用,否则它会假定它没有作为终端服务会话运行。

您将通过WTSRegisterSessionNotification注册会话更新通知。这将允许您的应用程序被立即通知远程连接已被打开或关闭到桌面会话,您的应用程序正在运行。有关示例C#代码,请参阅here

对于使用WTSRegisterSessionNotification的一些很好的Delphi Win32实验代码,请参阅此page

7

看到类似的问题,我问:How to check if we’re running on battery?

因为如果你使用电池运行,你还需要禁用动画。

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

再检查,如果你使用电池运行:

/// <summary> 
/// Indicates if we're running on battery power. 
/// If we are, then disable CPU wasting things like animations, background operations, network, I/O, etc 
/// </summary> 
public static Boolean IsRunningOnBattery 
{ 
    get 
    { 
     PowerLineStatus pls = System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus; 
     if (pls == PowerLineStatus.Offline) 
     { 
     //Offline means running on battery 
     return true; 
     } 
     else 
     { 
     return false; 
     } 
    } 
} 

,你可以只组合为一个:

public Boolean UseAnimations() 
{ 
    return 
     (!System.Windows.Forms.SystemInformation.TerminalServerSession) && 
     (System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus != PowerLineStatus.Offline); 
} 

注:这个问题已被询问(Determine if a program is running on a Remote Desktop

相关问题