frmexample2.vb

来自「Microsoft Mobile Development Handbook的代码」· VB 代码 · 共 99 行

VB
99
字号
Imports Microsoft.VisualBasic
Imports System
Imports System.Windows.Forms
Imports System.Diagnostics
Imports System.Collections
Imports System.IO
Imports System.Threading

Namespace CodeForChapter11cs
  Public Partial Class frmExample2
	  Inherits Form
	Public Sub New()
	  InitializeComponent()
	End Sub

	Private allFiles As ArrayList = New ArrayList() ' holds the results
	Private stopRequested As Boolean = False ' user hit the cancel button

	Private Sub menuItem2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles menuItem2.Click
	  ' cancel
	  stopRequested = True
	End Sub

	' re-write this menu click event handler method
	Private Sub menuItem1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles menuItem1.Click
	  ' load list
	  label1.Text = ""
	  listBox1.DataSource = Nothing
	  stopRequested = False

	  Dim t As Thread = New Thread(AddressOf Me.GetAllFiles) 'delegate inference
	  t.Name = "Worker: allFiles populator"
	  t.Start()
	End Sub

	'... extracted form menu event hnadler and is now Control Invoked
	Private Sub UpdateBox(ByVal sender As Object, ByVal e As EventArgs)
	  label1.Text = allFiles.Count.ToString()
	  listBox1.DataSource = allFiles
	  Debug.WriteLine("Got results " & listBox1.Items.Count.ToString())
	End Sub

	Private Sub GetAllFiles()
	  allFiles.Clear()
	  Me.PopulateAllFilesFor("\")
	  Debug.WriteLine("Finished")

	  Me.Invoke(New EventHandler(AddressOf Me.UpdateBox)) 'at the end, update the UI
	End Sub

	Private Sub PopulateAllFilesFor(ByVal path As String)
	  If stopRequested Then
		Debug.WriteLine("cancelled 1")
		Return
	  End If
	  Debug.WriteLine("Processing new path")

	  allFiles.Add(path)

	  Dim files As String()
	  files = Directory.GetFiles(path)
	  allFiles.AddRange(files)

	  Debug.WriteLine(allFiles.Count.ToString())

	  ' replaces previously commented out line
	  Me.Invoke(New EventHandler(Of LabelEventArgs)(AddressOf UpdateLabel), New Object(){label1, New LabelEventArgs(allFiles.Count)})


	  If stopRequested Then
		Debug.WriteLine("cancelled 2")
		Return
	  End If

	  For Each subDirectory As String In Directory.GetDirectories(path)
		Me.PopulateAllFilesFor(subDirectory) 'recursion
		If stopRequested Then
		  Debug.WriteLine("cancelled 3")
		  Return
		End If
	  Next subDirectory
	End Sub

	#Region "Supports Control.Invoke"
	' Could have used delegate with int parameter but best follow the .NET pattern of having an EventArgs class
	Private Class LabelEventArgs
		Inherits EventArgs
	  Public Sub New(ByVal items As Integer)
		NumberOfItems = items
	  End Sub
	  Public NumberOfItems As Integer
	End Class

	Private Sub UpdateLabel(ByVal sender As Object, ByVal e As LabelEventArgs)
	  label1.Text = e.NumberOfItems.ToString()
	End Sub
	#End Region
  End Class
End Namespace

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?