如何在Do Loop语句运行时保持表单响应 [英] How to keep a form responsive whilst a Do Loop statement is running
问题描述
如果运行以下代码,将会看到在Do[...]Loop
语句运行时无法单击Button2
:
If you run the following code you will see that you can not click Button2
whilst the Do[...]Loop
statement is running:
Imports Microsoft.Office.Interop
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlApp As New Excel.Application
xlApp.Visible = True
Dim wb1 As Excel.Workbook
wb1 = xlApp.Workbooks.Open("C:\Book1.xlsx")
Dim wsSheet1 As Excel.Worksheet
wsSheet1 = CType(wb1.Sheets(1), Excel.Worksheet)
Do
wsSheet1.Cells.Copy()
wsSheet1.Cells.PasteSpecial(Paste:=Excel.XlPasteType.xlPasteValues)
Loop
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
MsgBox("Hello")
End Sub
End Class
在Do[...]Loop
语句运行时如何保持Form1
响应?
How do you keep Form1
responsive whilst the Do[...]Loop
statement is running?
推荐答案
为了在Do[...]Loop
语句运行时保持表单响应,您需要使用
In order to keep your form responsive whilst the Do[...]Loop
statement is running you need to run it on a separate thread using the Task class.
首先创建一个新方法并将Do[...]Loop
语句放置在该方法中:
First create a new method and place the Do[...]Loop
statement in that method:
Private Sub CopyCells(ByVal worksheet As Excel.Worksheet)
Do
worksheet.Cells.Copy()
worksheet.Cells.PasteSpecial(Paste:=Excel.XlPasteType.xlPasteValues)
Loop
End Sub
然后,您可以使用任务来调用此方法.Factory.StartNew :
Task.Factory.StartNew(Sub() CopyCells(wsSheet1))
我也将不再使用MsgBox
并使用MessageBox.Show
. MsgBox
对于VB6存在,并且最终还是委派给MessageBox
,因此使用MessageBox.Show
有意义:
I would also move away from using MsgBox
and use MessageBox.Show
. MsgBox
exists for VB6 and ends up delegating to MessageBox
anyway so makes sense to use MessageBox.Show
:
MessageBox.Show("Hello")
完整来说,您的代码将类似于以下内容:
In full your code would look something similar to this:
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlApp As New Excel.Application
xlApp.Visible = True
Dim wb1 As Excel.Workbook
wb1 = xlApp.Workbooks.Open("C:\Book1.xlsx")
Dim wsSheet1 As Excel.Worksheet
wsSheet1 = CType(wb1.Sheets(1), Excel.Worksheet)
Task.Factory.StartNew(Sub() CopyCells(wsSheet1))
End Sub
Private Sub CopyCells(ByVal worksheet As Excel.Worksheet)
Do
worksheet.Cells.Copy()
worksheet.Cells.PasteSpecial(Paste:=Excel.XlPasteType.xlPasteValues)
Loop
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
MessageBox.Show("Hello")
End Sub
End Class
请注意,您必须导入
System.Threading.Tasks
才能使用Task
类.
这篇关于如何在Do Loop语句运行时保持表单响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!