Checking for workstation lock/unlock change with c#

前端 未结 4 1725
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 22:27

DUPLICATE: How can I programmatically determine if my workstation is locked?

How can I detect (during runtime) when a Windows user has locked their

相关标签:
4条回答
  • 2020-12-09 22:29

    A SessionSwitch event may be your best bet for this. Check the SessionSwitchReason passed through the SessionSwitchEventArgs to find out what kind of switch it is and react appropriately.

    0 讨论(0)
  • 2020-12-09 22:31

    You can get this notification via a WM_WTSSESSION_CHANGE message. You must notify Windows that you want to receive these messages via WTSRegisterSessionNotification and unregister with WTSUnRegisterSessionNotification.

    These posts should be helpful for a C# implementation.

    http://pinvoke.net/default.aspx/wtsapi32.WTSRegisterSessionNotification

    http://blogs.msdn.com/shawnfa/archive/2005/05/17/418891.aspx

    http://bytes.com/groups/net-c/276963-trapping-when-workstation-locked

    0 讨论(0)
  • 2020-12-09 22:46

    You absolutely don't need WM_WTSSESSION_CHANGE Just use internal WTTS apis.

    0 讨论(0)
  • 2020-12-09 22:52

    You can use ComponentDispatcher as an alternative way to get those events.

    Here's an example class to wrap that.

    public class Win32Session
    {
        private const int NOTIFY_FOR_THIS_SESSION = 0;
        private const int WM_WTSSESSION_CHANGE = 0x2b1;
        private const int WTS_SESSION_LOCK = 0x7;
        private const int WTS_SESSION_UNLOCK = 0x8;
    
        public event EventHandler MachineLocked;
        public event EventHandler MachineUnlocked;
    
        public Win32Session()
        {
            ComponentDispatcher.ThreadFilterMessage += ComponentDispatcher_ThreadFilterMessage;
        }
    
        void ComponentDispatcher_ThreadFilterMessage(ref MSG msg, ref bool handled)
        {
            if (msg.message == WM_WTSSESSION_CHANGE)
            {
                int value = msg.wParam.ToInt32();
                if (value == WTS_SESSION_LOCK)
                {
                    OnMachineLocked(EventArgs.Empty);
                }
                else if (value == WTS_SESSION_UNLOCK)
                {
                    OnMachineUnlocked(EventArgs.Empty);
                }
            }
        }
    
        protected virtual void OnMachineLocked(EventArgs e)
        {
            EventHandler temp = MachineLocked;
            if (temp != null)
            {
                temp(this, e);
            }
        }
    
        protected virtual void OnMachineUnlocked(EventArgs e)
        {
            EventHandler temp = MachineUnlocked;
            if (temp != null)
            {
                temp(this, e);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题