c#后台工作者& &;eventhandler一起-搜索USB设备

本文关键字:搜索 USB 设备 一起 eventhandler 后台 工作者 | 更新日期: 2023-09-27 18:01:16

我是第一次使用BackGroundWorker和EventHandler。我不知道我做得对不对。我想搜索连接的USB设备(只是有一定的VID &;PID)。因为调试程序不想进入bw_worker_dowork循环。

我也使用WPF与MVVM方法-为信息。

请帮忙。我做的对不对?

    BackgroundWorker bw_worker;
    USBmiddleware cs = new USBmiddleware();

    public Windows1ViewModel()
    {
        bw_worker = new BackgroundWorker();
        bw_worker.DoWork += new DoWorkEventHandler(bw_worker_dowork);
        bw_worker.WorkerReportsProgress = true;
        bw_worker.WorkerReportsProgress = true;

    }
    void bw_worker_dowork(object sender, DoWorkEventArgs e)
    {
        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();
        // Do something while waiting for events
        System.Threading.Thread.Sleep(20000000);
    }
    void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
    {
        cs.FindDevices();
    }
    void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
    {
        cs.FindDevices();
    }     

c#后台工作者& &;eventhandler一起-搜索USB设备

你没有启动你的BackgroundWorker !BackgroundWorker。RunWorkerAsync方法

对不起。问题就在那里:

:

"SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'"

:

"SELECT * FROM Win32_DeviceChangeEvent WHERE       EventType = 2"

以前只在我的USB耳机上工作,现在也为我的其他设备工作:)对不起。