Getting logged-on username from a service

前端 未结 4 2013
孤街浪徒
孤街浪徒 2021-01-03 10:05

I have a service that I had to log on to the local admin to install. The pupose of this service to log when a user is logging in or out to record their username. I finally f

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 10:28

    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 like this:

    protected override void OnSessionChange(SessionChangeDescription changeDescription)
    {
        string username = GetUsername(changeDescription.SessionId);
        //continue with any other thing you wish to do
    }
    

提交回复
热议问题