正在等待连接HID读卡器

时间:2014-10-30 19:32:04

标签: c# wmi hid

我正在编写一个需要将HID读卡器连接到系统的应用程序。当应用程序启动时已连接读卡器时,一切正常,所以我知道我可以正确找到设备。 (我正在使用PM> Install-Package hidlibrary中的HID类。)

我想添加一项功能,如果找不到卡片阅读器,程序将显示连接读卡器的提示。

这是我的第一次尝试:

public class App : Application
{
    public static List<HidDevice> HidDeviceList;

    // Block until device is plugged in
    static ManualResetEvent m_WaitForPlugin = new ManualResetEvent(false);

    // WMI Watcher for actual plug-in event
    static ManagementEventWatcher watcher = new ManagementEventWatcher();

    [STAThread()]
    static void Main()
    {
        ShowSplashScreen();

        FindCardReader();

        CloseSplashScreen();

        new App();
    }

    public App() : base()
    {

        StartupUri = new System.Uri("MainWindow.xaml", UriKind.Relative);
        Run();
    }

    private static void FindCardReader()
    {

        ShowOnSplashScreen("Searching for card reader");

        do
        {
            int VendorID = Convert.ToInt32(Settings.Default.ReaderVID, 16); // 0x0801
            int ProductID = Convert.ToInt32(Settings.Default.ReaderPID, 16); // 0x0002
            HidDeviceList = HidDevices.Enumerate(VendorID, ProductID).ToList();

            if (HidDeviceList.Count > 0) {
                break;
            }

            ShowOnSplashScreen("Please attach card reader...");
            SetupWatcher();
            m_WaitForPlugin.WaitOne();

        } while (HidDeviceList.Count == 0);
    }

    private static void SetupWatcher()
    {
        WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
        watcher.EventArrived += new EventArrivedEventHandler(delegate(Object sender, EventArrivedEventArgs e)
        {
            ShowOnSplashScreen("New device detected!");
            m_WaitForPlugin.Set();
        });
        watcher.Query = query;
        watcher.Start();
    }
FindCardReader()阻止Main按预期阻止,但在插入新设备时似乎永远不会发出信号。(我在代理中设置断点并且从未命中。)

我不确定如何自己测试WMI观察者(我在PowerShell中测试了查询,它似乎工作)。我也尝试在new Thread中启动它,但结果是一样的。

1 个答案:

答案 0 :(得分:0)

事实证明,此代码中存在非常明显的死锁。我重新构建了整个系统,以避免出现问题,而不是添加额外的线程来处理锁定。