我已经编写了以下代码,以完成在机器上导出打印机详细信息的任务。下面的代码可以正常工作。
通常,生成打印机详细信息文件需要花费几秒钟或更长时间,因此,我想在标签或文本框中显示此过程的状态(例如“正在生成文件。请稍候...”, “文件已生成。”等)
我无法使用以下代码在标签上获得正确的状态。它直接显示“文件已生成”状态。但是,如果将消息框放在while循环之前和之后,则可以正常工作。
任何帮助都非常有帮助。谢谢。
Label1.Text = "Status: File is being generated. Please wait.."
Dim pPrintBrm As New ProcessStartInfo
pPrintBrm.FileName = "C:\Windows\System32\spool\tools\PrintBrm.exe"
pPrintBrm.Arguments = " " & "-B" & " " & "-F" & " " &
My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport"
pPrintBrm.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(pPrintBrm)
Dim exists As Boolean = File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport")
MessageBox.Show("before while " & exists)
While (exists = "False")
exists = File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport")
End While
MessageBox.Show("after while " & exists)
If File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport") Then
Label1.Text = "Status: File is generated"
Else
Label1.Text = "Status: Failed"
End If
答案 0 :(得分:0)
使用BackgroundWorker组件,然后在Background Worker的DoWork事件中执行此代码,并通过BackgroundWorker.ReportProgress()在标签上显示所有更新状态
答案 1 :(得分:0)
您可以使用Async/Await使应用程序在循环中保持响应状态:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label1.Text = "Status: File is being generated. Please wait.."
Dim pPrintBrm As New ProcessStartInfo
pPrintBrm.FileName = "C:\Windows\System32\spool\tools\PrintBrm.exe"
pPrintBrm.Arguments = " " & "-B" & " " & "-F" & " " &
My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport"
pPrintBrm.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(pPrintBrm)
Dim exists As Boolean
Do
Await Task.Delay(250) ' <-- code pauses here, but the UI is still responsive and updates
exists = File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport")
Loop While (Not exists)
If exists Then
Label1.Text = "Status: File is generated"
Else
Label1.Text = "Status: Failed" ' <-- how can you ever get here with the above loop?!
End If
End Sub
请注意,子声明已标记为“异步”。