如何在C#控制台应用中捕获Windows 10锁屏/解锁事件?
捕获Windows锁屏/解锁事件的C#控制台应用实现方案
要在C#控制台应用中捕获锁屏、解锁事件,确实可以通过WM_WTSSessionChange消息实现。由于控制台应用本身没有消息循环,需要借助隐藏窗口来接收系统消息,以下是具体实现步骤和代码:
核心思路
Windows系统会在会话状态变化(如锁屏、解锁)时发送WM_WTSSessionChange消息,我们需要:
- 创建一个隐藏窗口来接收系统消息
- 注册会话状态变化通知
- 重写窗口消息处理方法,识别锁屏/解锁事件
完整代码实现
1. 项目配置
如果使用.NET Core/.NET 5+,需在项目文件中添加:
<UseWindowsForms>true</UseWindowsForms>
同时引用System.Windows.Forms程序集。
2. 代码实现
using System; using System.Threading.Tasks; using System.Windows.Forms; using System.Runtime.InteropServices; namespace AutoClicker { public class SessionEventWindow : Form { // 系统消息常量 private const int WM_WTSSessionChange = 0x02B1; private const int WTS_SESSION_LOCK = 0x7; private const int WTS_SESSION_UNLOCK = 0x8; private const int NOTIFY_FOR_THIS_SESSION = 0; // 导入Windows API [DllImport("wtsapi32.dll", SetLastError = true)] private static extern bool WTSRegisterSessionNotification(IntPtr hWnd, int dwFlags); [DllImport("wtsapi32.dll", SetLastError = true)] private static extern bool WTSUnregisterSessionNotification(IntPtr hWnd); // 自定义事件 public event EventHandler SessionLocked; public event EventHandler SessionUnlocked; public SessionEventWindow() { // 隐藏窗口 ShowInTaskbar = false; WindowState = FormWindowState.Minimized; // 注册会话状态通知 WTSRegisterSessionNotification(Handle, NOTIFY_FOR_THIS_SESSION); } protected override void WndProc(ref Message m) { base.WndProc(ref m); // 处理会话变化消息 if (m.Msg == WM_WTSSessionChange) { int eventType = m.WParam.ToInt32(); switch (eventType) { case WTS_SESSION_LOCK: SessionLocked?.Invoke(this, EventArgs.Empty); break; case WTS_SESSION_UNLOCK: SessionUnlocked?.Invoke(this, EventArgs.Empty); break; } } } protected override void Dispose(bool disposing) { // 注销通知 WTSUnregisterSessionNotification(Handle); base.Dispose(disposing); } } class Program { static void Main(string[] args) { using var eventWindow = new SessionEventWindow(); // 绑定锁屏事件处理逻辑 eventWindow.SessionLocked += (s, e) => { Console.WriteLine("[事件] 屏幕已锁定"); // 在这里添加你的处理,比如暂停自动点击操作 }; // 绑定解锁事件处理逻辑 eventWindow.SessionUnlocked += (s, e) => { Console.WriteLine("[事件] 屏幕已解锁"); // 在这里恢复自动点击操作 }; Console.WriteLine("应用启动,开始监听锁屏/解锁事件..."); Console.WriteLine("按任意键退出程序"); // 同时运行消息循环和控制台按键监听 var inputTask = Task.Run(() => Console.ReadKey()); Application.Run(eventWindow); inputTask.Wait(); } } }
关键说明
- 隐藏窗口:通过
Form类创建的窗口会自动维护消息循环,确保能接收系统发送的WM_WTSSessionChange消息 - API调用:
WTSRegisterSessionNotification用于向系统注册会话状态通知,NOTIFY_FOR_THIS_SESSION表示只监听当前用户会话的变化 - 权限要求:无需管理员权限,普通用户即可注册自身会话的状态通知
- 消息循环:
Application.Run(eventWindow)启动Windows消息循环,保证窗口能持续接收消息
内容的提问来源于stack exchange,提问作者user19532719
相关产品推荐
相关产品推荐

