我有以下代码,它应该加载表单,每秒更改一次文本,然后在结束时运行shutdown命令。 取消按钮将取消关闭(或只是关闭窗体,阻止关闭命令运行)。
Public Class FRM_SHUTDOWN
Private Sub FRM_SHUTDOWN_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LBL_TIMER.Text = "Shutting Down in 6..."
End Sub
Private Sub FRM_SHUTDOWN_Shown(sender As Object, e As EventArgs) Handles Me.Shown
LBL_TIMER.Text = "Shutting Down in 6..."
Threading.Thread.Sleep(1000)
LBL_TIMER.Text = "Shutting Down in 5..."
Threading.Thread.Sleep(1000)
LBL_TIMER.Text = "Shutting Down in 4..."
Threading.Thread.Sleep(1000)
LBL_TIMER.Text = "Shutting Down in 3..."
Threading.Thread.Sleep(1000)
LBL_TIMER.Text = "Shutting Down in 2..."
Threading.Thread.Sleep(1000)
LBL_TIMER.Text = "Shutting Down in 1..."
Threading.Thread.Sleep(1000)
LBL_TIMER.Text = "Windows is Shutting Down"
Threading.Thread.Sleep(1000)
'System.Diagnostics.Process.Start("shutdown", "-s -t 0")
MessageBox.Show("Shutdown instant would happen here")
End Sub
Private Sub BTN_CANCEL_Click(sender As Object, e As EventArgs) Handles BTN_CANCEL.Click
'System.Diagnostics.Process.Start("shutdown", "-a")
MessageBox.Show("Cancel shutdown command")
Me.Close()
End Sub
结束班
所以它实际上并没有显示'停止'按钮或倒数计时器!
任何人都可以解释原因吗?
答案 0 :(得分:2)
您的应用程序正忙着等待,因此无法重绘表单(添加LBL_TIMER.Refresh
会有所帮助,但这不是正确的方法)。您需要在与UI线程分开的线程中进行等待。
最简单的方法是使用后台工作程序。这将为您处理UI线程和后台线程之间的一些同步。
在表单加载时运行worker,然后在worker DoWork
方法中等待。
您可以使用ReportProgress
方法
Private WithEvents _worker As New BackgroundWorker With
{.WorkerReportsProgress = True, .WorkerSupportsCancellation = True}
Private _cancelled As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
_worker.RunWorkerAsync()
End Sub
Private Sub _worker_DoWork(sender As Object, e As DoWorkEventArgs) Handles _worker.DoWork
_cancelled = False
For i As Integer = 6 To 1 Step -1
CType(sender, BackgroundWorker).ReportProgress(i)
Threading.Thread.Sleep(1000)
If CType(sender, BackgroundWorker).CancellationPending Then Exit Sub
Next
End Sub
Private Sub _worker_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles _worker.ProgressChanged
Label1.Text = "Shutting down in " & e.ProgressPercentage
End Sub
Private Sub _worker_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles _worker.RunWorkerCompleted
If _cancelled Then
MessageBox.Show("Shutdown was cancelled")
Else
MessageBox.Show("Shutdown instant would happen here")
End If
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
_cancelled = True
_worker.CancelAsync()
End Sub