Imports System.IO
Public Class Form1
Dim watcher As New FileSystemWatcher()
Dim FileChanged As Boolean
Delegate Sub UpdateFileChangeDelegate()
Private Sub Button_Click(sender As System.Object, e As System.EventArgs) Handles Button.Click
watcher.Path = "C:\Demo Image Pool"
watcher.NotifyFilter = NotifyFilters.LastWrite
watcher.Filter = "DemoImage.raw"
watcher.SynchronizingObject = Me
AddHandler watcher.Changed, AddressOf OnChanged
watcher.EnableRaisingEvents = True
TextBoxMessage.Text = "Looking for file change"
'The code below relates to Application
Dim myProcess As New Process()
myProcess.StartInfo.FileName = "CaptureImage.exe"
myProcess.StartInfo.Arguments = "60 500 8 100"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.CreateNoWindow = True
myProcess.StartInfo.RedirectStandardInput = True
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.Start()
myProcess.WaitForExit(28000)
myProcess.Close()
While 1
If FileChanged = True Then
TextBoxMessage.Text = "Hello World"
Exit While
End If
End While
End Sub
Private Shared Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
Form1.FileChanged = True
End Sub
End Class
在上面的代码中,CaptureImage.exe在FileWatcher位置捕获一个新图像“DemoImage.raw”。我在File Change事件处理程序中将Boolean变量更改为true,但是在主线程中,我无法退出循环。我认为,原因是变量FileChanged没有被改变或者变化没有被反映出来。如果有人能指出我哪里出错了,我将不胜感激。表单只包含一个按钮和文本框。
谢谢!
答案 0 :(得分:1)
问题是您使用的是默认实例,默认实例是特定于线程的。因此,您实际上是在创建一个新的Form1实例并设置其字段而不是您已打开的Form1实例。无论如何,任何表单都不应引用自己的默认实例,因此应该Me.FileChanged
而不是Form1.FileChanged
。
除此之外,我真的希望这只是一些非常脏的测试代码,因为那里有一个繁忙的等待循环,这是你可能编写的最糟糕的代码。