i tried one of the solutions in this thread Detecting USB drive insertion and removal using windows service and c#. but i stil get errors, because of the thread-unsafe call to windows forms control.
here is my code
private void initWatchers()
{
WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery);
insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
insertWatcher.Start();
WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery);
removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
removeWatcher.Start();
}
and in the event handlers i started the backgroundworker
private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}
void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}
after the backgroundworker is finished, i do access the controls in the windows form
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// access some controls of my windows form
}
so now im still getting errors because of the unsafe calling of the controls. any idea why?