如何在VB.Net中检测用户不活动

时间:2019-07-26 18:59:35

标签: vb.net

当鼠标不活动时,我开始计时。如果鼠标不活动10秒钟,请刷新webbrowser1并将时间重置为“ 0”,然后从“ 0”重新开始。当鼠标处于活动状态时,时间重新开始为“ 0”。我有这个密码。

Option Strict On
Option Explicit On
Imports System.Runtime.InteropServices

Public Class Form1
    <DllImport("user32.dll")> Shared Function GetLastInputInfo(ByRef plii As LASTINPUTINFO) As Boolean
    End Function

    <StructLayout(LayoutKind.Sequential)> Structure LASTINPUTINFO
        <MarshalAs(UnmanagedType.U4)> Public cbSize As Integer
        <MarshalAs(UnmanagedType.U4)> Public dwTime As Integer
    End Structure

    Dim lastInputInf As New LASTINPUTINFO()

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Timer1.Interval = 1000
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        lastInputInf.cbSize = Marshal.SizeOf(lastInputInf)
        lastInputInf.dwTime = 0
        GetLastInputInfo(lastInputInf)
        Label1.Text = CInt((Environment.TickCount - lastInputInf.dwTime) / 1000).ToString
        If CInt((Environment.TickCount - lastInputInf.dwTime) / 1000) > 10 Then 'check if it has been 11 seconds
            'Do whatever commands here that you want to happen
            'if no user input is detected in last 10 seconds.
            Timer1.Stop()
            WebBrowser1.Navigate("http://www.google.com")

        End If
    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

您非常接近解决方案。您必须重新启动计时器。查看代码中的注释。

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    lastInputInf.cbSize = Marshal.SizeOf(lastInputInf)
    lastInputInf.dwTime = 0
    GetLastInputInfo(lastInputInf)
    Label1.Text = CInt((Environment.TickCount - lastInputInf.dwTime) / 1000).ToString
    If CInt((Environment.TickCount - lastInputInf.dwTime) / 1000) > 10 Then 'check if it has been 11 seconds
        'Do whatever commands here that you want to happen
        'if no user input is detected in last 10 seconds.
        ' No need to stop the Timer1, it is already stopped.
        'Timer1.Stop()
        WebBrowser1.Navigate("http://www.google.com")
    End If
    ' Here you must restart the Timer1, otherwise the Timer1_tick will not be called again.
    Timer1.Start()
End Sub