Windows service: Get username when user log on

前端 未结 3 569
傲寒
傲寒 2021-01-28 02:02

my windows service should save the name of the user, which logon/logoff at the moment. The following code works for me but didn\'t save the username:

protected o         


        
3条回答
  •  佛祖请我去吃肉
    2021-01-28 02:20

    I ran into a similar problem while building a Windows Service. Just like you, I had the Session ID and needed to get the corresponding username. After several unsuccessful solution hereon SO, I ran into this particular answer and it inspired my solution:

    Here's my code (all of them residing inside a class; in my case, the class inheriting ServiceBase).

        [DllImport("Wtsapi32.dll")]
        private static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WtsInfoClass wtsInfoClass, out IntPtr ppBuffer, out int pBytesReturned);
        [DllImport("Wtsapi32.dll")]
        private static extern void WTSFreeMemory(IntPtr pointer);
    
        private enum WtsInfoClass
        {
            WTSUserName = 5, 
            WTSDomainName = 7,
        }
    
        private static string GetUsername(int sessionId, bool prependDomain = true)
        {
            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;
        }
    

    With the above code in your class, you can simply get the username in the method you're overriding by calling

    string username = GetUsername(changeDescription.SessionId);
    

提交回复
热议问题