问题
I have been researching for a couple of weeks now, on and off, on how to determine the computer name of the user that is logged in via remote desktop.
I have an application that users run on a terminal server environment, and I would like to capture and store the name of the computer that they are using to connect to the terminal server with.
So far, I have not been able to find code or create my own that can do this, and I think I am just not asking the right questions.
Any assistance would be greatly appreciated.
PS. I am using C# and .Net 4.0
回答1:
Okay so I have found a solution at http://www.amasso.info/?p=165
Code reproduced below...
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);
}
}
回答2:
I know this is an old post, but this is what I use and it'll work on Win 2000 thru Windows 2008R2. I have not confirmed W2012 yet, but it should also be OK:
System.Environment.GetEnvironmentVariable("ClientName") It returns a string of the client name that's connected. Works for TS & XenApp.
Hope it'll save others time. The accepted answer is overkill.
回答3:
See this question. The Cassia library is another option if you'd like to avoid the P/Invokes or get additional information about the session.
来源:https://stackoverflow.com/questions/8147904/c-sharp-determine-remote-desktop-login-users-computer-name