Okay, brilliant, thanks for clarifying that...
so the below works well and makes sense, I guess the addhandler creates its own magical accessible instance of 'thefilewatcher' which is why it didnt makes sense to me. (surely it would overwrite each time, but it doesnt so good)
Code:
Public Function fnWatchFolders() As Boolean
For i As Integer = 0 To lstFolders.Items.Count - 1
Dim TheFileWatcher As New FileSystemWatcher(lstFolders.Items(i), "*.txt")
TheFileWatcher.NotifyFilter = NotifyFilters.FileName
TheFileWatcher.EnableRaisingEvents = True
AddHandler TheFileWatcher.Changed, AddressOf OnChanged
AddHandler TheFileWatcher.Created, AddressOf OnChanged
AddHandler TheFileWatcher.Renamed, AddressOf OnChanged
AddHandler TheFileWatcher.Deleted, AddressOf OnChanged
MyFSWList.Add(TheFileWatcher) 'Adding this to the collection keeps a reference to it, thus stopping it going out of scope_
Next
cmdWatch.Enabled = False
cmdStopWatch.Enabled = True
cmdAddFolder.Enabled = False
cmdRemoveFolder.Enabled = False
cmdExit.Enabled = False
Return True
End Function
Now moving back to an earlier query, which is providing visual notification of the changes, so lstchanges.items.add(strchangeItem) This fails to work and the program just halts as we talked about earlier, so i tried RTFM and invoked the following, but this just doesnt not seem to work, no doubt have got this wrong somewhere! (commented in magenta)
Code:
Public Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs) Handles TheFileWatcher.Changed, TheFileWatcher.Created, TheFileWatcher.Renamed, TheFileWatcher.Deleted
Dim strChangeItem As String = ("Change Detected: " & e.FullPath & " : was " & e.ChangeType.ToString("G"))
MsgBox(strChangeItem)
Debug.Print(strChangeItem)
'lstChanges.Items.Add(strChangeItem) 'addChangedDataToChangedListboxInvoker(strChangeItem) ' doesn't work as expected yet. End Sub
Private Delegate Sub addChangedDataToChangedListboxInvoker(ByVal strChangeItem As String)
Private Sub addChangedDataToChangedListbox(strChangeItem As String)
If Me.lstChanges.InvokeRequired Then
Me.lstChanges.Invoke(New addChangedDataToChangedListboxInvoker(AddressOf addChangedDataToChangedListbox))
Else
Me.lstChanges.Items.Add(strChangeItem)
End If
End Sub
Also, I'm guessing we need to use that collection created above, when we want to stop the filewatcher from running,
Obviously here, its not going to be an instance anymore so will fail, as we want to use the collection of TheFileWatcher(s) and set .enableraisingevents to false for each of the items in the collection somehow ?
Code:
Private Sub cmdStopWatch_Click(sender As System.Object, e As System.EventArgs) Handles cmdStopWatch.Click
TheFileWatcher.EnableRaisingEvents = False
cmdWatch.Enabled = True
cmdStopWatch.Enabled = False
cmdAddFolder.Enabled = True
cmdRemoveFolder.Enabled = True
cmdExit.Enabled = True
End Sub