using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace webImTray { /// /// Base class for a form that wants to be notified of Windows /// session lock / unlock events /// public class LockNotificationForm : Form { // from wtsapi32.h private const int NotifyForThisSession = 0; // from winuser.h private const int SessionChangeMessage = 0x02B1; private const int SessionLockParam = 0x7; private const int SessionUnlockParam = 0x8; [DllImport("wtsapi32.dll")] private static extern bool WTSRegisterSessionNotification(IntPtr hWnd, int dwFlags); [DllImport("wtsapi32.dll")] private static extern bool WTSUnRegisterSessionNotification(IntPtr hWnd); // flag to indicate if we've registered for notifications or not private bool registered = false; /// /// Is this form receiving lock / unlock notifications /// protected bool ReceivingLockNotifications { get { return registered; } } /// /// Unregister for event notifications /// protected override void Dispose(bool disposing) { if (registered) { WTSUnRegisterSessionNotification(Handle); registered = false; } base.Dispose(disposing); return; } /// /// Register for event notifications /// protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); // WtsRegisterSessionNotification requires Windows XP or higher bool haveXp = Environment.OSVersion.Platform == PlatformID.Win32NT && (Environment.OSVersion.Version.Major > 5 || (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1)); if (haveXp) registered = WTSRegisterSessionNotification(Handle, NotifyForThisSession); return; } /// /// The windows session has been locked /// protected virtual void OnSessionLock() { return; } /// /// The windows session has been unlocked /// protected virtual void OnSessionUnlock() { return; } /// /// Process windows messages /// protected override void WndProc(ref Message m) { // check for session change notifications if (m.Msg == SessionChangeMessage) { if (m.WParam.ToInt32() == SessionLockParam) OnSessionLock(); else if (m.WParam.ToInt32() == SessionUnlockParam) OnSessionUnlock(); } base.WndProc(ref m); return; } } }