我正在尝试在禁用时更改按钮的文本。我按下按钮时会调用一个后台工作器,我试图让按钮被禁用5秒钟,按钮上的文字显示再次启用按钮之前剩余的时间。
以下是我的代码,删除了无关的位:
Private Sub btnDispense_Click(sender As System.Object, e As System.EventArgs) Handles btnDispense.Click
btnDispense.Enabled = False
BackgroundWorker1.RunWorkerAsync()
' Lots of my irrelevant code in here.
Private Sub bgwWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
' Changes button text from 5 to 1, with threading to keep time.
btnDispense.Text = "Dispense (-1) [5]"
Threading.Thread.Sleep(1000)
btnDispense.Text = "Dispense (-1) [4]"
Threading.Thread.Sleep(1000)
btnDispense.Text = "Dispense (-1) [3]"
Threading.Thread.Sleep(1000)
btnDispense.Text = "Dispense (-1) [2]"
Threading.Thread.Sleep(1000)
btnDispense.Text = "Dispense (-1) [1]"
Threading.Thread.Sleep(1000)
End Sub
Private Sub bgwWorker_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
' Called when the BackgroundWorker is completed.
btnDispense.Enabled = True
End Sub
当我尝试运行它时,没有错误,所以我的语法没问题。我唯一的问题是按钮上的文字没有改变;这是因为按钮被禁用了吗?我不知道如何开展这项工作。
非常感谢任何帮助!
答案 0 :(得分:0)
使用您的示例:
Private Sub btnDispense_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDispense.Click
bgwWorker.WorkerReportsProgress = True
btnDispense.Enabled = False
bgwWorker.RunWorkerAsync()
End Sub
Private Sub bgwWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwWorker.DoWork
Dim worker As System.ComponentModel.BackgroundWorker = CType(sender, System.ComponentModel.BackgroundWorker)
worker.ReportProgress(0, "Dispense (-1) [5]")
Threading.Thread.Sleep(1000)
worker.ReportProgress(0, "Dispense (-1) [4]")
Threading.Thread.Sleep(1000)
worker.ReportProgress(0, "Dispense (-1) [3]")
Threading.Thread.Sleep(1000)
worker.ReportProgress(0, "Dispense (-1) [2]")
Threading.Thread.Sleep(1000)
worker.ReportProgress(0, "Dispense (-1) [1]")
Threading.Thread.Sleep(1000)
End Sub
Private Sub bgwWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgwWorker.ProgressChanged
btnDispense.Text = e.UserState.ToString
End Sub
Private Sub bgwWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgwWorker.RunWorkerCompleted
btnDispense.Enabled = True
End Sub