本文介绍了如何从SessionID获取Windows用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C#中是否有一种方法可以从给定的会话ID中检索用户名?(系统上运行的任何会话)
Is there a method in C# to retrieve the user name from a given session id? (any session running on the system)
Win API函数 WTSQuerySessionInformation 可以做到这一点,但是我正在C#中搜索此功能.
The Win API function WTSQuerySessionInformation does this, but I'm searching for this functionality in C#.
推荐答案似乎没有.NET集成方法.因此,这是使用Windows终端服务API的当前解决方案:
There seems to be no .NET integrated method for this. So this is the current solution, using Windows Terminal services API:
[DllImport("Wtsapi32.dll")] private static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WtsInfoClass wtsInfoClass, out System.IntPtr ppBuffer, out int pBytesReturned); [DllImport("Wtsapi32.dll")] private static extern void WTSFreeMemory(IntPtr pointer); public enum WtsInfoClass { 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, } public static string GetUsernameBySessionId(int sessionId, bool prependDomain) { IntPtr buffer; int strLen; string username = "SYSTEM"; if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSUserName, out buffer, out strLen) && strLen > 1) { username = Marshal.PtrToStringAnsi(buffer); WTSFreeMemory(buffer); if (prependDomain) { if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSDomainName, out buffer, out strLen) && strLen > 1) { username = Marshal.PtrToStringAnsi(buffer) + "\\" + username; WTSFreeMemory(buffer); } } } return username; }更多推荐
如何从SessionID获取Windows用户名?
发布评论