2011-11-16 123 views
4

對於如何確定通過遠程桌面登錄的用戶的計算機名稱,我一直在研究現在幾個星期的開啓和關閉。C#確定遠程桌面登錄用戶的計算機名稱

我有一個應用程序,用戶在終端服務器環境中運行,我想捕獲並存儲他們用來連接到終端服務器的計算機的名稱。

到目前爲止,我一直無法找到可以做到這一點的代碼或創建自己的代碼,我想我只是沒有提出正確的問題。

任何援助將不勝感激。

PS。我使用C#和.NET 4.0

回答

7

好了,我已經找到了解決辦法,在http://www.amasso.info/?p=165

下面的代碼複製...

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Security.Principal; 
using System.Net; 

namespace loginName 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent()); 
      MessageBox.Show(wp.Identity.Name); // Username 
      MessageBox.Show(GetTerminalServerClientNameWTSAPI()); // Remote Host PC Name 

     } 

     private static string GetTerminalServerClientNameWTSAPI() 
     { 

      const int WTS_CURRENT_SERVER_HANDLE = -1; 

      IntPtr buffer = IntPtr.Zero; 
      uint bytesReturned; 

      string strReturnValue = ""; 
      try 
      { 
       WTSQuerySessionInformation(IntPtr.Zero, WTS_CURRENT_SERVER_HANDLE, WTS_INFO_CLASS.WTSClientName, out buffer, out bytesReturned); 
       strReturnValue = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(buffer); 
      } 

      finally 
      { 
       buffer = IntPtr.Zero; 
      } 

      return strReturnValue; 
     } 

     enum WTS_INFO_CLASS 
     { 
      WTSInitialProgram, 
      WTSApplicationName, 
      WTSWorkingDirectory, 
      WTSOEMId, 
      WTSSessionId, 
      WTSUserName, 
      WTSWinStationName, 
      WTSDomainName, 
      WTSConnectState, 
      WTSClientBuildNumber, 
      WTSClientName, 
      WTSClientDirectory, 
      WTSClientProductId, 
      WTSClientHardwareId, 
      WTSClientAddress, 
      WTSClientDisplay, 
      WTSClientProtocolType 

     } 

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

    } 
} 
+0

WTS_CURRENT_SERVER_HANDLE是0,不是-1。它應該只被指定爲第一個參數。第二個參數可以是WTS_CURRENT_SESSION - 這是-1,而不是0. – Alex

2

this question。如果您想避免P/Invokes或獲得有關會話的其他信息,Cassia library是另一種選擇。

+0

我在發佈我的查詢的同時發現了該鏈接。謝謝 –

4

我知道這是一箇舊帖子,但這是我使用的,它將在Win 2000上通過Windows 2008R2工作。我還沒有確認W2012,但它也應該是OK:

System.Environment.GetEnvironmentVariable(「ClientName」)它返回一個連接的客戶端名稱的字符串。適用於TS & XenApp。

希望它能節省時間。接受的答案是矯枉過正。

+0

謝謝,我不知道這一點。矯枉過正被低估。 –