So I have some code which checks for the plugin and removal of a USB device.
public void Main_Shown(object sender, EventArgs e)
{
var watcheradd = new ManagementEventWatcher();
var queryadd = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
watcheradd.EventArrived += new EventArrivedEventHandler(watcher_deviceadded);
watcheradd.Query = queryadd;
watcheradd.Start();
var watcherremove = new ManagementEventWatcher();
var queryremove = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
watcherremove.EventArrived += new EventArrivedEventHandler(watcher_deviceremoved);
watcherremove.Query = queryremove;
watcherremove.Start();
}
I was wondering is there anyway I can stop the watchremove
and watcheradd
loops before my program exits to prevent an exception by the stop code within:
private void Exit_Main(object sender, EventArgs e)
{
Process p = new System.Diagnostics.Process();
ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo();
si.RedirectStandardInput = false;
si.CreateNoWindow = true;
si.UseShellExecute = false;
si.FileName = "adb.exe";
si.Arguments = "kill-server";
p = Process.Start(si);
p.WaitForExit();
Application.Exit();
//EXIT APPLICATION!!!
}
as Main_Shown.deviceadd.Stop();
isn't the correct syntax or way of doing this.
The result should safely stop the above loops and then allow the program to exit without an exception.
Got a solution. So I needed to add
ManagementEventWatcher watcheradd = new ManagementEventWatcher();
WqlEventQuery queryadd = new WqlEventQuery();
ManagementEventWatcher watcherremove = new ManagementEventWatcher();
WqlEventQuery queryremove = new WqlEventQuery();
above the class and that set the classes to global. So now it exits without a problem using the code below.
`si.FileName = "adb.exe";
si.Arguments = "kill-server";
p = Process.Start(si);
p.WaitForExit();
watcherremove.Stop();
watcheradd.Stop();
Application.Exit();
//EXIT APPLICATION!!`
Thanks everyone for your help.