From WindowsService how can I find currently logged in user from C#?

妖精的绣舞 提交于 2019-12-03 04:01:28
Dmitry

1) Cassia should be able to give you a list of currently logged in users including RDC.

foreach (ITerminalServicesSession sess in new TerminalServicesManager().GetSessions())
{
    // sess.SessionId
    // sess.UserName
}

2) WMI (SO answer)

Select * from Win32_LogonSession

3) PInvoke to WTSEnumerateSessions

4) Enumerate all instances of "explorer.exe" and get the owner using PInvoke (OpenProcessHandle).

Process[] processes = Process.GetProcessesByName("explorer");

This is a bit hacky. WMI can also be used for this.

It might be a good idea to set winmgmt as a dependency for your service if you decided to go with solution that uses WMI.

You might want to look at Cassia:

Cassia is a .NET library for accessing the native Windows Terminal Services API (now the Remote Desktop Services API). It can be used from C#, Visual Basic.NET, or any other .NET language.

and:

Enumerating terminal sessions and reporting session information including connection state, user name, client name, client display details ...

Try this,

http://www.codeproject.com/KB/vb/Windows_Service.aspx

Pretty simple idea, just loops through active processes to find 'explorer.exe' and lists the user thats its running under. Might have to adjust if you have multiple users.

Using the Local Security Authority to Enumerate User Sessions in .NET http://www.codeproject.com/KB/system/LSAEnumUserSessions.aspx

WTSQuerySessionInformation Function http://msdn.microsoft.com/en-us/library/aa383838%28v=vs.85%29.aspx

A list of users currently logged into console sessions can be retrieved via WMI. You'll need to add a reference to System.Management.dll:

public static List<string> GetLoggedOnUsers(CacheLevel level)
{
    const int ConsoleSession = 2;

    string logonQuery = "SELECT * FROM Win32_LogonSession WHERE LogonType = " + ConsoleSession;

    ManagementObjectSearcher searcher = new ManagementObjectSearcher(logonQuery);

    List<string> userNames = new List<string>();

    foreach (ManagementBaseObject logon in searcher.Get())
    {
        string logonId = logon.Properties["LogonId"].Value.ToString();

        string userQuery = "ASSOCIATORS OF {Win32_LogonSession.LogonId=" + logonId + "} "
                           + "WHERE AssocClass=Win32_LoggedOnUser Role=Dependent";

        ManagementObjectSearcher searcher2 = new ManagementObjectSearcher(userQuery);

        foreach (ManagementBaseObject user in searcher2.Get())
        {
            string name = user.Properties["FullName"].Value.ToString();

            userNames.Add(name);
        }
    }

    return userNames.Distinct().ToList();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!