在窗体上放置一个 Timer、ProgressBar 和一个 BackgroundWorker。您要做的第一件事是防止表单在程序启动时变得可见。将此代码粘贴到表单类中:
Protected Overrides Sub SetVisibleCore(ByVal value As Boolean)
If Not Me.IsHandleCreated Then
value = False
Me.CreateHandle
End If
MyBase.SetVisibleCore(value)
End Sub
使用计时器开始工作。设置其 Interval 和 Enabled 属性,添加 Tick 事件处理程序:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Me.Show()
ProgressBar1.Visible = True
Me.Enabled = False
BackgroundWorker1.RunWorkerAsync()
End Sub
这使得表单在作业启动并启动后台工作程序时可见。将 BGW 的 WorkerReportsProgress 属性设置为 True 并添加 3 个事件处理程序:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'' Do stuff here, call BackgroundWorker1.ReportProgress to update the PB
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ProgressBar1.Value = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
ProgressBar1.Visible = False
Me.Enabled = True
Me.Hide()
End Sub
由您来填写 DoWork 事件处理程序的代码。让它完成这 15 项工作,请务必调用 BackgroundWorker1.ReportProgess 以便更新进度条。这就是 ProgressChanged 事件处理程序所做的。RunWorkerCompleted 事件处理程序再次隐藏表单。
您可以在 NotifyIcon 的上下文菜单项事件中调用 Show() 方法,以便用户可以使您的表单再次可见。在允许用户退出您的应用程序的上下文菜单项中调用 Application.Exit()。确保在 BGW 运行时禁用它。或者实施一种彻底停止工作的方法。