5

我正在开发一个应用程序,并试图检测工作站何时被锁定,例如用户按下 Windows + L 键。

我知道锁定事件具有价值

  WTS_SESSION_LOCK 0x7

但我不知道如何使用它。我在网上搜索过,但一无所获。

4

2 回答 2

6

您应该使用命名空间SystemEvents中的类Microsoft.Win32,尤其是SystemEvents.SessionSwitch事件。

SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;  // Subscribe to the SessionSwitch event

static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
    if (e.Reason == SessionSwitchReason.SessionLock)
        // Add your session lock "handling" code here
}

更新

如果您需要在 Winforms 应用程序的程序启动时激活此事件:

static class Program
{
    [STAThread]
    private static void Main()
    {
        SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;  // Subscribe to the SessionSwitch event

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
    {
        if (e.Reason == SessionSwitchReason.SessionLock)
            // Add your session lock "handling" code here
    }
}
于 2013-07-25T02:01:40.700 回答
1

Finnallly 设法在 VB 上做到这一点:D

首先,您需要导入库:

Imports System
Imports Microsoft.Win32
Imports System.Windows.Forms

然后添加处理程序:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    AddHandler SystemEvents.SessionSwitch, AddressOf SessionSwitch_Event

End Sub

最后,您创建捕获它的子:

Private Sub SessionSwitch_Event(ByVal sender As Object, ByVal e As SessionSwitchEventArgs)

    If e.Reason = SessionSwitchReason.SessionLock Then
        MsgBox("Locked")
    End If
    If e.Reason = SessionSwitchReason.SessionUnlock Then
        MsgBox("Unlocked")
    End If
End Sub

最后你删除处理程序:

Private Sub closing_event(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
    RemoveHandler SystemEvents.SessionSwitch, AddressOf SessionSwitch_Event
End Sub
于 2013-07-26T00:35:49.577 回答