C# 获取所有已登录系统的用户名

复制代码
[DllImport("wtsapi32.dll")]
static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] string pServerName);

[DllImport("wtsapi32.dll")]
static extern void WTSCloseServer(IntPtr hServer);

[DllImport("wtsapi32.dll")]
static extern Int32 WTSEnumerateSessions(
    IntPtr hServer,
    [MarshalAs(UnmanagedType.U4)] Int32 Reserved,
    [MarshalAs(UnmanagedType.U4)] Int32 Version,
    ref IntPtr ppSessionInfo,
    [MarshalAs(UnmanagedType.U4)] ref Int32 pCount);

[DllImport("wtsapi32.dll")]
static extern void WTSFreeMemory(IntPtr pMemory);

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

[StructLayout(LayoutKind.Sequential)]
private struct WTS_SESSION_INFO
{
    public Int32 SessionID;

    [MarshalAs(UnmanagedType.LPStr)]
    public string pWinStationName;

    public WTS_CONNECTSTATE_CLASS State;
}

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

public enum WTS_CONNECTSTATE_CLASS
{
    WTSActive,
    WTSConnected,
    WTSConnectQuery,
    WTSShadow,
    WTSDisconnected,
    WTSIdle,
    WTSListen,
    WTSReset,
    WTSDown,
    WTSInit
}

public static List<string> GetLoginedUsers(string serverName)
{
    IntPtr serverHandle = IntPtr.Zero;
    List<string> resultList = new List<string>();
    serverHandle = WTSOpenServer(serverName);

    try
    {
        IntPtr sessionInfoPtr = IntPtr.Zero;
        IntPtr userPtr = IntPtr.Zero;
        IntPtr domainPtr = IntPtr.Zero;
        Int32 sessionCount = 0;
        Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref sessionInfoPtr, ref sessionCount);
        Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));
        IntPtr currentSession = sessionInfoPtr;
        uint bytes = 0;

        if (retVal != 0)
        {
            for (int i = 0; i < sessionCount; i++)
            {
                WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO));
                currentSession += dataSize;

                WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes);
                WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes);

                var domain = Marshal.PtrToStringAnsi(domainPtr);
                var username = Marshal.PtrToStringAnsi(userPtr);
                
                if(!string.IsNullOrWhiteSpace(username))
                    resultList.Add(username);

                WTSFreeMemory(userPtr);
                WTSFreeMemory(domainPtr);
            }

            WTSFreeMemory(sessionInfoPtr);
        }
    }
    finally
    {
        WTSCloseServer(serverHandle);
    }

    return resultList;
}

void Main()
{
    GetLoginedUsers(Environment.MachineName).Dump();
}

// Define other methods and classes here
复制代码

 

posted on   空明流光  阅读(1418)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2019-11-19 c++ 调用 sqlcipher
2019-11-19 c++ 调用 sqlite
2018-11-19 AutoCompleteExtender 使用示例

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示