我有一个Windows窗体应用程序,将打开其他窗体,但只会显示窗体几秒钟(用户可配置).我通常会做类似threading.thread.sleep(n)的事情,但是当这样做时,表单控件不会仅加载白色背景节目,而且我也一直在阅读这不是我作为用户所做的最佳实践在线程唤醒之前,不会对输入进行操作.
我遇到过使用System.Timers.Timer(n)的人,但是我很难让这个为我工作,表单只会立即打开和关闭(你只能看到一个闪存,因为表单打开然后关闭) .
我使用的代码是:
Private Shared tmr As New System.Timers.Timer
aForm.Show()
tmr = New System.Timers.Timer(aSleep * 60 * 60)
tmr.Enabled = True
aForm.Close()
Run Code Online (Sandbox Code Playgroud)
这都包含在传递表单和定义的运行时的Private子中.
我的目的是让主应用程序从任务栏运行,然后任务栏调用将在指定时间段内显示的表单之一,关闭表单,然后调用另一个表单.
有没有能够指出我正确的方向为什么表格打开然后关闭而不通过定义的运行时间(我已经测试了10秒),或者有更好的方式来做我正在寻找的东西?
非常感谢您的帮助.
马特
文档说有一个Elapsed事件处理程序,在时间流逝时被调用.您将关闭处理程序中的表单:
http://msdn.microsoft.com/en-us/library/system.timers.timer%28VS.85%29.aspx
我刚刚写了一个小例子来说明你需要做什么:
http://www.antiyes.com/close-form-after-10-seconds
下面是相关代码,完整的解决方案可以从文章中下载.
表格1代码
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim frm2 As New Form2()
frm2.ShowDialog()
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)
表格2代码
Imports System.Timers
Public Class Form2
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
Dim tmr As New System.Timers.Timer()
tmr.Interval = 5000
tmr.Enabled = True
tmr.Start()
AddHandler tmr.Elapsed, AddressOf OnTimedEvent
End Sub
Private Delegate Sub CloseFormCallback()
Private Sub CloseForm()
If InvokeRequired Then
Dim d As New CloseFormCallback(AddressOf CloseForm)
Invoke(d, Nothing)
Else
Close()
End If
End Sub
Private Sub OnTimedEvent(ByVal sender As Object, ByVal e As ElapsedEventArgs)
CloseForm()
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)
当然,要使此代码工作,您需要使用按钮进行表单设置.