How do I get events to execute on the "main thread"

Posted by William DiStefano on Stack Overflow See other posts from Stack Overflow or by William DiStefano
Published on 2010-05-21T16:53:40Z Indexed on 2010/05/21 19:40 UTC
Read the original article Hit count: 237

Filed under:
|
|
|

I have 2 classes, one is frmMain a windows form and the other is a class in vb.NET 2003.

frmMain contains a start button which executes the monitor function in the other class. My question is, I am manually adding the event handlers -- when the events are executed how do I get them to excute on the "main thread". Because when the tooltip balloon pops up at the tray icon it displays a second tray icon instead of popping up at the existing tray icon. I can confirm that this is because the events are firing on new threads because if I try to display a balloon tooltip from frmMain it will display on the existing tray icon.

Here is a part of the second class (not the entire thing):

Friend Class monitorFolders
    Private _watchFolder As System.IO.FileSystemWatcher = New System.IO.FileSystemWatcher
    Private _eType As evtType

    Private Enum evtType
        changed
        created
        deleted
        renamed
    End Enum

    Friend Sub monitor(ByVal path As String)
            _watchFolder.Path = path

            'Add a list of Filter to specify
            _watchFolder.NotifyFilter = IO.NotifyFilters.DirectoryName
            _watchFolder.NotifyFilter = _watchFolder.NotifyFilter Or IO.NotifyFilters.FileName
            _watchFolder.NotifyFilter = _watchFolder.NotifyFilter Or IO.NotifyFilters.Attributes

            'Add event handlers for each type of event that can occur
            AddHandler _watchFolder.Changed, AddressOf change
            AddHandler _watchFolder.Created, AddressOf change
            AddHandler _watchFolder.Deleted, AddressOf change
            AddHandler _watchFolder.Renamed, AddressOf Rename

            'Start watching for events
            _watchFolder.EnableRaisingEvents = True
    End Sub
    Private Sub change(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)
        If e.ChangeType = IO.WatcherChangeTypes.Changed Then
        _eType = evtType.changed
            notification()
        End If
        If e.ChangeType = IO.WatcherChangeTypes.Created Then
        _eType = evtType.created
            notification()
        End If
        If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
        _eType = evtType.deleted
            notification()
        End If
    End Sub
    Private Sub notification()
         _mainForm.NotifyIcon1.ShowBalloonTip(500, "Folder Monitor", "A file has been " + [Enum].GetName(GetType(evtType), _eType), ToolTipIcon.Info)
    End Sub
End Class

© Stack Overflow or respective owner

Related posts about .NET

Related posts about vb