我正在开发一个将在一定时间内注销用户的内容。我声明了Application.Idle
Private Sub Application_Idle(sender As Object, e As EventArgs)
Timer.Interval = My.Settings.LockOutTime
Timer.Start()
End Sub
然后,在表单加载事件
上调用它Private Sub ctlManagePw_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
AddHandler System.Windows.Forms.Application.Idle, AddressOf Application_Idle
End Sub
在计时器上
Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
Try
If My.Settings.TrayIcon = 1 Then
Me.ParentForm.Controls.Remove(Me)
control_acPasswords()
_Main.NotifyIcon.Visible = True
_Main.NotifyIcon.ShowBalloonTip(1, "WinVault", "You've been locked out due to innactivity", ToolTipIcon.Info)
End If
'Stop
Timer.Stop()
Timer.Enabled = False
'Flush memory
FlushMemory()
Catch ex As Exception
'Error is trapped. LOL
Dim err = ex.Message
End Try
End Sub
这个问题是每当空闲事件结束时,我仍然会收到通知我已经再次锁定和/或应用程序已进入空闲事件。
control_acPasswords()
是注销用户控件
这里是我释放记忆的地方
Declare Function SetProcessWorkingSetSize Lib "kernel32.dll" (ByVal process As IntPtr, ByVal minimumWorkingSetSize As Integer, ByVal maximumWorkingSetSize As Integer) As Integer
Public Sub FlushMemory()
Try
GC.Collect()
GC.WaitForPendingFinalizers()
If (Environment.OSVersion.Platform = PlatformID.Win32NT) Then
SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1)
Dim myProcesses As Process() = Process.GetProcessesByName(Application.ProductName)
Dim myProcess As Process
For Each myProcess In myProcesses
SetProcessWorkingSetSize(myProcess.Handle, -1, -1)
Next myProcess
End If
Catch ex As Exception
Dim err = ex.Message
End Try
End Sub
如果我在Timer_Tick事件Exception上放置MsgBox(ex.Message)
,我会继续
Object reference not set to an instance of an object
我的预期结果是,只要表单进入空闲事件,它就会得到My.Settings.LockOutTime
的时间间隔或时间,这是一个分钟值并存储为60000
1 minute
或{ {1}}并启动计时器。现在在Timer_Tick上,如果间隔结束,则60 seconds
用户。
我处理事件有什么不对吗?
答案 0 :(得分:3)
Application.Idle事件多次触发。 Winforms每次从消息队列中检索所有消息并清空它。问题是,它启动的第二次和随后的时间,你正在启动一个已经启动的计时器。这没有任何效果,您必须重置它,以便在编程的时间间隔内再次开始滴答。容易做到:
Private Sub Application_Idle(sender As Object, e As EventArgs)
Timer.Interval = My.Settings.LockOutTime
Timer.Stop()
Timer.Start()
End Sub
下一个问题,可能是异常的原因,是您明确必须在表单关闭时取消订阅该事件。它不是自动的,Application.Idle是一个静态事件。使用FormClosed事件:
Protected Overrides Sub OnFormClosed(ByVal e As System.Windows.Forms.FormClosedEventArgs)
Timer.Stop()
RemoveHandler Application.Idle, AddressOf Application_Idle
MyBase.OnFormClosed(e)
End Sub
答案 1 :(得分:2)
除了Hans的回答:当用户不再闲置时,您似乎不会停止计时器运行。也就是说,当我空闲时计时器启动,但如果我回来,我会在计时器停止时被锁定。
当用户再次激活时,您需要确保停止计时器。