WPF 检测Windows用户会话状态:登录界面、非登录界面
1 主动获取Windows用户会话状态:登录界面、非登录界面,没有直接的Api接口,通过获取当前的前台窗台判断,
条件: 获取不到、UWP界面且窗体名字:windows 窗体类名windows.ui.core.corewindow。
经过压测可靠
using System; using System.Runtime.InteropServices; using System.Text; /// <summary> /// 用户会话状态 /// </summary> public class UserSessionState { [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); /// <summary> /// 锁屏状态 /// </summary> public static bool IsSessionLock() { var hWnd = GetForegroundWindow(); if (hWnd == IntPtr.Zero) { return true; } int length = GetWindowTextLength(hWnd); StringBuilder sb = new StringBuilder(length + 1); GetWindowText(hWnd, sb, sb.Capacity); var s = sb.ToString(); Log.Info($"[用户状态] 窗体名称 : {s}"); if (string.IsNullOrWhiteSpace(s)) return false; StringBuilder className = new StringBuilder(256); // 256为缓冲区大小,可以根据需要调整 int nRet = GetClassName(hWnd, className, className.Capacity); if (nRet != 0) { Log.Info($"[用户状态] 窗体类名 : {className}"); var cN = className.ToString(); if (string.IsNullOrWhiteSpace(cN)) { return false; } var uwp = cN.ToLower().Trim().StartsWith("windows.ui.core.corewindow"); var windows = s.ToLower().Trim().StartsWith("windows"); var screenSaver = uwp && windows; return screenSaver; } return false; } }
2 被动监听,这个有自带的事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | SystemEvents.SessionSwitch += SystemEvents_SessionSwitch; private void SystemEvents_SessionSwitch( object sender, SessionSwitchEventArgs e) { try { switch (e.Reason) { case SessionSwitchReason.SessionLock: DeviceStatusInfo.SessionLogon = true ; break ; case SessionSwitchReason.SessionUnlock: default : DeviceStatusInfo.SessionLogon = false ; break ; } Log.Info($ "进入登录界面状态:{DeviceStatusInfo.SessionLogon}" ); DeviceStatusInfo.SessionSwitchReasonEvent?.Invoke(sender, e); } catch (Exception ex) { Log.Error(ex); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗