在未使用一段时间后关闭应用程序

时间:2016-06-27 13:42:11

标签: vb.net

我正在vb.net中开发一个应用程序,我希望能够判断用户是否在主表单上,但暂时没有做任何事情。 有没有办法检查用户是否正在使用该应用程序,如果没有,则注销?

我已经对它进行了一些搜索,如果我可以开发这个代码,我得不到任何结论......所以你对我应该如何解决这个问题有任何想法?

1 个答案:

答案 0 :(得分:-1)

您可以创建一个具有计时器的类,该计时器将监视更新并在需要时结束执行。

Public Class IdleWatcher
    ' TODO: Implements IDisposable
    ' TODO: and dispose _timer
    Private _timer As System.Threading.Timer
    Private _enabled As Boolean
    Private _lastEvent As DateTime
    Public Sub New()
        _timer = New System.Threading.Timer(AddressOf watch)
        _enabled = False
        Timeout = 0
    End Sub
    Public Event Idle(sender As Object)
    Public Property Timeout As Long
    Public Property Enabled As Boolean
        Get
            Return _enabled
        End Get
        Set(value As Boolean)
            If value Then
                _lastEvent = DateTime.Now
                _timer.Change(0, 1000)
            Else
                _timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite)
            End If
        End Set
    End Property
    Private Sub watch()
        If DateTime.Now.Subtract(_lastEvent).TotalMilliseconds > Timeout Then
            Enabled = false
            ' raise an event so the form can handle it and log out
            RaiseEvent Idle(Me)
        End If
    End Sub
    Public Sub Refresh()
        _lastEvent = DateTime.Now
    End Sub
End Class

它可以在您的表单应用程序中使用,如下所示:

Public Class Form1
    Private WithEvents watcher As New IdleWatcher
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        watcher.Timeout = 5000 ' 5 second timeout
        watcher.Enabled = True
    End Sub
    Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
        watcher.Refresh()
    End Sub
    Private Sub watcher_idle(sender As Object) Handles watcher.Idle
        ' If login.show is modal, then you don't need to call MainForm.Close()
        ' This will depend on your implementation
        Login.Show()
        MainForm.Close()
    End Sub
End Class

这至少会监控Form1上的鼠标移动。如果要跨多个表单共享实例,以便可以从其他表单中刷新它,则可以使该类成为单例。它是一个很好的候选人。

根据您希望的彻底程度,您还可以从表单上的其他控件(如TextBoxes和Buttons)的事件处理程序中调用Refresh。

更进一步,您可以将所有控件子类化,并在基类中的所有相关UI事件处理程序中添加Refresh调用。如果您发现自己在整个地方刷新,这将节省大量工作。

相关问题