VSTO中应用的例子,希望给大家有点启发
在VB.net中WinForm+Backgroundworker+StatusStrip范例
以上是在VSTO的窗体
下面是代码部分
Imports System.ComponentModel
Public Class Form_backgroundworker
Dim ShowFlag As Boolean = True
Dim actCell As Excel.Range
Private Sub Form_backgroundworker_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CenterToScreen()
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.WorkerSupportsCancellation = True
End Sub
Private Sub Form_backgroundworker_Closed(sender As Object, e As EventArgs) Handles Me.Closed
If BackgroundWorker1.IsBusy Then
ShowFlag = False
BackgroundWorker1.CancelAsync()
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
For j As Integer = 1 To 100
If BackgroundWorker1.CancellationPending Then
e.Cancel = True
Return
End If
Try
actCell.Offset(j - 1).Value = j
Catch ex As Exception
End Try
worker.ReportProgress(j)
System.Threading.Thread.Sleep(200)
Next j
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Dim changeNum As Integer = e.ProgressPercentage
Dim ss As String = "发送中..." + changeNum.ToString() + "/100"
If ShowFlag Then
Me.Invoke(Sub()
ToolStripStatusLabel1.Text = ss
ToolStripProgressBar1.Value = changeNum
Label2.Text = ss
End Sub
)
End If
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Dim outStr As String = String.Empty
If e.Error IsNot Nothing Then
outStr = e.Error.Message
ElseIf e.Cancelled Then
outStr = "任务已取消"
Else
outStr = "完成"
End If
If ShowFlag Then
Me.Invoke(Sub()
ToolStripStatusLabel1.Text = outStr
Label2.Text = outStr
Button1.Enabled = True
End Sub
)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
ToolStripProgressBar1.Maximum = 100
ToolStripProgressBar1.Minimum = 0
ToolStripProgressBar1.Value = 0
ShowFlag = True
If Not BackgroundWorker1.IsBusy Then
actCell = xlapp.ActiveCell
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If BackgroundWorker1.IsBusy Then
ShowFlag = False
BackgroundWorker1.CancelAsync()
End If
End Sub
End Class