【问题标题】:detecting usb-device insertion and removal in c#在 C# 中检测 USB 设备的插入和移除
【发布时间】:2014-11-17 15:23:07
【问题描述】:

我尝试了此线程Detecting USB drive insertion and removal using windows service and c# 中的一种解决方案。但由于对 Windows 窗体控件的线程不安全调用,我仍然遇到错误。

这是我的代码

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

}

在事件处理程序中我启动了后台工作程序

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

backgroundworker 完成后,我确实可以访问 windows 窗体中的控件

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

所以现在我仍然会因为控件的不安全调用而出错。知道为什么吗?

【问题讨论】:

    标签: c# usb backgroundworker


    【解决方案1】:

    这是因为 GUI 元素位于应用程序的 GUI 线程中,而您正试图从 BackGroundWorker 线程访问它们。您必须使用委托来处理 BackgroundWorker 中的 GUI 元素。例如:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多