Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Hide this button
CancelCopying.Visible = False
End Sub
' The CancelCopying button sits exactly on top of
' the StartCopying button. So we can see one or the
' other, but not both.
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
' Because 'f2' is created on the background thread
' We will have no cross thread problems updating it
' from here.
' Form2 though was created through the IDE.
Dim f2 As New Form2
f2.ProgressBar1.Minimum = 1
f2.ProgressBar1.Value = 1
f2.ProgressBar1.Step = 1
f2.TopMost = True
f2.Show()
Dim theExtentions() As String = {"*.jpg", "*.bmp"}
f2.Label1.Text = "Please wait ... Gathering file information"
Application.DoEvents()
f2.Refresh()
For Each currentExt As String In theExtentions
Dim theFiles() As String = Directory.GetFiles("C:\Images\")
'Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), currentExt, SearchOption.AllDirectories)
f2.ProgressBar1.Maximum = theFiles.Length
For Each currentFile As String In theFiles
Try
f2.Label1.Text = "Copying: " & currentFile
My.Computer.FileSystem.CopyFile(currentFile, "c:\tempfiles\" & System.IO.Path.GetFileName(currentFile), True)
Catch ex As Exception
MsgBox("Error copying " & currentFile)
End Try
f2.ProgressBar1.PerformStep()
Application.DoEvents()
f2.Refresh()
If BackgroundWorker1.CancellationPending Then
e.Cancel = True
Exit For
End If
Next
' f2.ProgressBar1.Value = 1
'' If BackgroundWorker1.CancellationPending Then
'e.Cancel = True
Exit For
'End If
Next
f2.Dispose()
End Sub
Private Sub StartCopying_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartCopying.Click
Me.BackgroundWorker1.WorkerSupportsCancellation = True
Me.BackgroundWorker1.RunWorkerAsync()
CancelCopying.Visible = True
End Sub
Private Sub CancelCopying_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CancelCopying.Click
BackgroundWorker1.CancelAsync()
CancelCopying.Visible = False
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If BackgroundWorker1.IsBusy Then
If MessageBox.Show("Copying still in progress. Do you want to cancel it?", "Cancel background work?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
BackgroundWorker1.CancelAsync()
Else
' Cancel the form close event
e.Cancel = True
End If
End If
End Sub
End Class