简体   繁体   English

如何在 c# windows 应用程序中获取 windows 解锁事件?

[英]How to get windows unlock event in c# windows application?

I want to track the windows unlock event in a windows application.我想在 Windows 应用程序中跟踪 Windows 解锁事件。 How is it done?它是如何完成的? What is the event used for that?事件是用来做什么的? Does I need to import any namespace for that?我需要为此导入任何命名空间吗?

While a user unlocks the windows, the application needs to do some tasks.当用户解锁窗口时,应用程序需要执行一些任务。

As posted in this StackOverflow answer: https://stackoverflow.com/a/604042/700926 you should take a look at the SystemEvents.SessionSwitch Event .正如在此 StackOverflow 答案中发布的: https : //stackoverflow.com/a/604042/700926您应该查看SystemEvents.SessionSwitch Event

Sample code can be found in the referred answer as well.示例代码也可以在参考答案中找到。

I just took the code shown in the referred StackOverflow answer for a spin and it seems to work on Windows 8 RTM with .NET framework 4.5.我只是拿了参考StackOverflow 答案中显示的代码进行了旋转,它似乎可以在带有 .NET 框架 4.5 的 Windows 8 RTM 上运行。

For your reference, I have included the complete sample code of the console application I just assembled.为了您的参考,我已经包含了我刚刚组装的控制台应用程序的完整示例代码。

using System;
using Microsoft.Win32;

// Based on: https://stackoverflow.com/a/604042/700926
namespace WinLockMonitor
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
            Console.ReadLine();
        }

        static void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
        {
            if (e.Reason == SessionSwitchReason.SessionLock)
            {
                //I left my desk
                Console.WriteLine("I left my desk");
            }
            else if (e.Reason == SessionSwitchReason.SessionUnlock)
            {
                //I returned to my desk
                Console.WriteLine("I returned to my desk");
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM