Search code examples
c#.netwindows-services

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


I am running a Windows service under the Administrator account and I would like to find out who is the currently logged in user. It will be different from the account the service is currently running under. Is there any easy way to get it from C#?

Those do not appear to work:

  • System.Security.Principal.WindowsIdentity.GetCurrent()
  • System.Environment.UserName

I am interested who is currently logged in with a console session.

I am not interested in other remote sessions, since this is not my case scenario.


Solution

  • 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.