Detecting insertion and removal of usb devices in C #

I tried one of the solutions in this thread Detecting USB Disk Insertion and Removal with Windows Service and C # . but I am getting errors because of unsafe thread call to manipulate window forms.

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 ran backgroundworker

private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
{ 
  this.backgroundWorker1.RunWorkerAsync();
}
void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
{
 this.backgroundWorker1.RunWorkerAsync();
}

      

after the backgroundworker finishes, I can access the controls on the windows form

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// access some controls of my windows form
}

      

so now im still getting errors due to unsafe calls to controls. any idea why?

+3


source to share


1 answer


This is because the GUI elements are on your application's GUI thread and you are trying to access them from the BackGroundWorker thread. You must use delegates to work with GUI elements from BackgroundWorker. For example:

    GUIobject.Dispatcher.BeginInvoke(
        (Action)(() => { string value = myTextBox.Text; }));

      



In RunWorkerCompleted, you are still trying to access GUI elements from BackGroundWorker.

0


source







All Articles