I'm trying to write a simple program that detects when files are changed in a folder (for another question here). It has a standard Windows with a TextBox and a couple buttons. Upon program start it calls .NET function FileSystemWatcher then sets up four event handlers for it. What I want is for the event handlers to write something to the TextBox, but VB.NET complains that shared functions can't access instance objects. I know a work-around in c++ by setting a global pointer to the instance which can be accessed by shared functions but can't think of a work around in VB. Anyone know how to do this?
The error is on line 30 of the code posted below.
Private Sub TurnOn() watcher = New FileSystemWatcher() ' Create a new FileSystemWatcher and set its properties. watcher.Path = txtFolder.Text ' Watch for changes in LastAccess and LastWrite times, and ' the renaming of files or directories. watcher.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName) ' watch all files. watcher.Filter = "*.*" ' Add event handlers. AddHandler watcher.Changed, AddressOf OnChanged AddHandler watcher.Created, AddressOf OnChanged AddHandler watcher.Deleted, AddressOf OnChanged AddHandler watcher.Renamed, AddressOf OnRenamed ' Begin watching. watcher.EnableRaisingEvents = True ' Wait for the user to quit the program. 'Console.WriteLine("Press 'q' to quit the sample.") 'While Chr(Console.Read()) <> "q"c 'End While 'Return True btnOnOff.Text = "OFF" End Sub Private Shared Sub OnChanged(source As Object, e As FileSystemEventArgs) ' Specify what is done when a file is changed, created, or deleted. txtFolder.Text = txtFolder.Text + "File: " & e.FullPath & " " & e.ChangeType '<<<< error on this line End Sub
The error message is
error BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.