在C#中检测USB设备的插入和移除 [英] detecting usb-device insertion and removal in c#

查看:603
本文介绍了在C#中检测USB设备的插入和移除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了该线程中的一种解决方案

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.

这是我的代码

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();
}

背景工作人员完成后,我确实访问了Windows窗体中的控件

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?

推荐答案

这是因为GUI元素位于应用程序的GUI线程中,并且您正尝试从BackGroundWorker线程访问它们.您必须使用Delegates来处理BackgroundWorker中的GUI元素.例如:

This is because GUI elements are in GUI thread of your app and you are trying to access them from the BackGroundWorker thread. You must use Delegates for working with GUI elements from your BackgroundWorker. For example:

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

在RunWorkerCompleted上,您仍在尝试从BackGroundWorker访问GUI元素.

On RunWorkerCompleted you are still trying to access GUI elements from the BackGroundWorker.

这篇关于在C#中检测USB设备的插入和移除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆