如何从SessionID获取Windows用户名?

编程入门 行业动态 更新时间:2024-10-11 05:21:01
本文介绍了如何从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用户名?

本文发布于:2023-11-07 02:09:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565270.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用户名   SessionID   Windows

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!