2014-10-30 132 views
1

我正在編寫一個需要將HID讀卡器連接到系統的應用程序。當應用程序啓動時已連接讀卡器時,一切正常,因此我知道我可以正確地找到設備。 (我正在使用PM> Install-Package hidlibrary的HID類別。)等待要連接的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(); 
    } 

MainFindCardReader()符合市場預期,但從來沒有出現在新的裝置插入到被標示(我把一個斷點在委託和它從來沒有。 )

我不知道如何自己測試WMI觀察器(我在PowerShell中測試了這個查詢,它似乎可以工作)。我也嘗試從new Thread開始,但結果是一樣的。

+0

你可以在定時循環(比如說,每2-3秒)測試一下你的'WqlEventQuery',看看'Win32_DeviceChangeEvent'實際上是否顯示在WMI中?之後,您可以嘗試使用您知道經常更改的東西來測試'ManagementEventWatcher',例如'Select * From Win32_LocalTime'。 – 2014-10-30 20:11:39

+0

你有沒有考慮過不同的查詢,可能是基於這一個:http://stackoverflow.com/questions/5278860/using-wmi-to-identify-which-device-caused-a-win32-devicechangeevent?rq=1? – 2014-10-30 20:13:07

+0

你看過一些[示例應用程序](https://github.com/mikeobrien/HidLibrary/blob/master/examples/MagtekCardReader/Program.cs#L23)如何處理連接/斷開連接嗎? – 2014-10-30 20:53:27

回答

0

事實證明,在這段代碼中存在非常明顯的死鎖。我已經重新構建了整個系統來避免這個問題,而不是添加額外的線程來處理鎖定。