VB.NET•Use the AddressOf Operator to Monitor Events

Listing 4. The AddressOf operator lets you specify event handlers that will fire when your declared events execute. This is the same as an event handler for a control on a form, except you declare them in code.

' Form level variable for
' the worker thread
Private _thread As Thread

Private Sub Connect_Click _
   (ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles Connect.Click

   If Thread.CurrentThread.Name _
      = "" Then
   Thread.CurrentThread.Name _
         = "UI Thread"
   End If

   Dim f As New ConnectForm
   If f.ShowDialog() = _
      DialogResult.OK Then
      f.Hide()
      f.Dispose()
      Application.DoEvents()

      Try

         Me.Cursor = Cursors.AppStarting
         Me.TreeView1.Cursor = _
            Cursors.WaitCursor

         ' Create an instance of 
         ' the TreeClass. 
         Dim tc As New TreeClass

         ' Add 3 Event Handlers. 
         AddHandler tc.UpdateProgress, _
            AddressOf Me.OnUpdateProgress
         AddHandler tc.AddNode, _
            AddressOf Me.OnAddNode
         AddHandler tc.ShowComplete, _
            AddressOf Me.ShowComplete

         ' Create a new Thread 
         ' When you create a new 
         ' Thread object, you simply pass 
         ' the name of the method which
         ' will run on the Thread, and then 
         ' call the thread's Start method

         _thread = New Thread _
            (AddressOf tc.LoadDatabaseTree)
         _thread.Name = "Non-UI Thread"
         _thread.Start()

      Catch ex As Exception
         MessageBox.Show _
            (ex.Message.ToString(), _
            Application.ProductName, _
            MessageBoxButtons.OK, _
            MessageBoxIcon.Information)
      End Try
   End If
End Sub