Service needs to detect if workstation is locked, and screen saver is active

后端 未结 3 749
傲寒
傲寒 2020-12-13 11:32

I\'m working on a service that needs to detect user states for all user(s) logged on to a single machine. Specifically, I want to check to see whether or not the screen save

3条回答
  •  孤城傲影
    2020-12-13 12:00

    As a serivce you can use the event OnSessionChange to catch all your relevant moments.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceProcess;
    using System.Diagnostics;
    
    namespace MyCode
    {
        class MyService : ServiceBase
        {
            public MyService()
            {
                this.CanHandleSessionChangeEvent = true;
            }
    
            protected override void OnSessionChange(SessionChangeDescription changeDescription)
            {
                switch (changeDescription.Reason)
                {
                    case SessionChangeReason.SessionLogon:
                        Debug.WriteLine(changeDescription.SessionId + " logon");
                        break;
                    case SessionChangeReason.SessionLogoff:
                        Debug.WriteLine(changeDescription.SessionId + " logoff");
                        break;
                    case SessionChangeReason.SessionLock:
                        Debug.WriteLine(changeDescription.SessionId + " lock");
                        break;
                    case SessionChangeReason.SessionUnlock:
                        Debug.WriteLine(changeDescription.SessionId + " unlock");
                        break;
                }
    
                base.OnSessionChange(changeDescription);
            }
        }
    }
    

    I'm sure it is possible to identify the user based on changeDescription.SessionId. But at the moment i don't know how...

    EDIT: This should be a possibilty

        public static WindowsIdentity GetUserName(int sessionId)
        {
            foreach (Process p in Process.GetProcesses())
            {
                if(p.SessionId == sessionId) {                    
                    return new WindowsIdentity(p.Handle);                          
                }                
            }
            return null;
        }
    

    MSDN Links

    • system.serviceprocess.servicebase.onsessionchange
    • system.serviceprocess.sessionchangedescription
    • system.serviceprocess.sessionchangereason

提交回复
热议问题