自动注销 Windows 表单

Automatic logout Windows Form

我有一个 Windows 表单应用程序是在 VB.NET 2010 年创建的,现在我需要实现自动注销。 我正在考虑使用一个计时器,该计时器随每个事件重置它或保存用户执行的每个操作的时间戳,问题是我如何检测每个事件。

该应用程序在 运行 时间和一些子 Windows 表单上创建了多个控件。

或者也许有人对如何实现该目标有更好的想法。(在一段时间不活动后从应用程序中注销用户。


编辑: Anthony 的代码从 C# 转换为 VB

Class MessageFilter
    Implements IMessageFilter
    Public Function PreFilterMessage(ByRef m As Message) As Boolean
        Const WM_KEYDOWN As Integer = &H100
        Const WM_MOUSELEAVE As Integer = &H2A3

        Select Case m.Msg
            Case WM_KEYDOWN, WM_MOUSELEAVE
                ' Do something to indicate the user is still active.
                Exit Select
        End Select

        ' Returning true means that this message should stop here,
        ' we aren't actually filtering messages, so we need to return false.
        Return False
    End Function
End Class

我在 WinForm Class 和单独的 Class 中尝试了这段代码,结果相同。 "Class 'MessageFilter' must implement 'Function PreFilterMessage(ByRef m As Message) As Boolean' for the interface 'System.Windows.Forms.IMessageFilter'."

已解决: 转换错误在函数签名中,必须如下所示。

Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage

编辑 2: 要删除过滤器,我以这种方式声明过滤器

Public Class Form1 
  Friend MyMsgFilter As New MessageFilter()
End Class

然后,当我需要添加消息过滤器时

Application.AddMessageFilter(MyMsgFilter)

以及何时需要删除它

Application.RemoveMessageFilter(MyMsgFilter)

非常感谢安东尼。

How can I detect every event?

你真的不需要每个事件。一些战略事件,如 MouseMove 和一些精心挑选的 KeyDown 处理程序应该涵盖它。我在这些事件中所做的只是更新一个全局时间戳变量,仅此而已。然后我还有一个计时器,它会经常触发并检查时间戳后的时间。

您可以通过创建消息过滤器并响应某些类型的频繁消息来实现此目的。示例代码是 C#,但翻译成 VB.NET.

应该不难
class MessageFilter : IMessageFilter
{
    public bool PreFilterMessage(ref Message m)
    {
        const int WM_KEYDOWN = 0x0100;
        const int WM_MOUSELEAVE = 0x02A3;

        switch (m.Msg)
        {
            case WM_KEYDOWN:
            case WM_MOUSELEAVE:
                // Do something to indicate the user is still active.
                break;
        }

        // Returning true means that this message should stop here,
        // we aren't actually filtering messages, so we need to return false.
        return false;
    }
}

在您的应用程序的某处,在用户登录后,您可以使用 Application.AddMessageFilter 方法注册消息过滤器。

Application.AddMessageFilter(new MessageFilter());

该示例仅侦听 KeyDown and MouseLeave 事件,这些事件都应该足够频繁地发生,但不会太频繁以至于消息过滤器会减慢整个应用程序。在 WinForms 应用程序中会触发大量消息,对发送的每条消息都做一些事情并不是一个好主意。