Home >Backend Development >C++ >How Can I Programmatically Monitor Workstation Lock Duration Across Different Platforms?
Use event handling to monitor workstation lock duration
Programmatically determining the duration of a workstation lockout is a common need in system monitoring and security applications. While multiple approaches exist, this article will explore a cross-platform solution using event handling.
In C#, you can use the SystemEvents.SessionSwitch
event to monitor the session status of the machine. When the reason for a session switch is SessionLock
or SessionUnlock
, the corresponding event handler can record the time and determine the duration of the lock.
<code class="language-csharp">using System; using Microsoft.Win32; namespace WorkstationLockMonitor { public class Program { static DateTime? _lockedTime; public static void Main() { SystemEvents.SessionSwitch += SystemEvents_SessionSwitch; } static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e) { if (e.Reason == SessionSwitchReason.SessionLock) { _lockedTime = DateTime.Now; } else if (e.Reason == SessionSwitchReason.SessionUnlock) { if (_lockedTime != null) { var duration = DateTime.Now - _lockedTime.Value; Console.WriteLine($"Workstation was locked for {duration.TotalMinutes} minutes"); } } } } }</code>
Similar mechanisms exist for subscribing to session change events in other programming languages such as Python or Java. For example, in Python, you can use the win32api
module:
<code class="language-python">import win32api from datetime import datetime _lockedTime = None def session_switch_callback(hwnd, msg, wParam, lParam): global _lockedTime if msg == win32api.WM_WTSSESSION_CHANGE: if lParam == win32api.WTS_SESSION_LOCK: _lockedTime = datetime.now() elif lParam == win32api.WTS_SESSION_UNLOCK: if _lockedTime is not None: duration = datetime.now() - _lockedTime print(f"Workstation was locked for {duration.total_seconds()} seconds") win32api.SetWinEventHook( win32api.EVENT_SYSTEM_SESSION_CHANGE, win32api.EVENT_SYSTEM_SESSION_CHANGE, 0, session_switch_callback, 0, 0, win32api.WINEVENT_OUTOFCONTEXT )</code>
By implementing these event-driven methods, you can programmatically track the duration of a workstation lockout, enabling you to monitor user activity patterns for security or performance analysis.
The above is the detailed content of How Can I Programmatically Monitor Workstation Lock Duration Across Different Platforms?. For more information, please follow other related articles on the PHP Chinese website!