C# 正在等待HID读卡器连接
我正在编写一个应用程序,需要将HID读卡器连接到系统。当应用程序启动时,读卡器已连接时,一切正常工作,因此我知道我可以正确找到设备。我正在使用PM>InstallPackageHidLibrary中的HID类 我想添加一个功能,如果找不到读卡器,程序将显示连接读卡器的提示 这是我第一次尝试:C# 正在等待HID读卡器连接,c#,wmi,hid,C#,Wmi,Hid,我正在编写一个应用程序,需要将HID读卡器连接到系统。当应用程序启动时,读卡器已连接时,一切正常工作,因此我知道我可以正确找到设备。我正在使用PM>InstallPackageHidLibrary中的HID类 我想添加一个功能,如果找不到读卡器,程序将显示连接读卡器的提示 这是我第一次尝试: public class App : Application { public static List<HidDevice> HidDeviceList; // Block u
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按预期安装在主块中,但在插入新设备时从未显示信号。我在委托中放置了一个断点,但它从未被命中
我不知道如何单独测试WMI watcher。我在PowerShell中测试了该查询,它似乎可以工作。我还尝试在一个新线程中启动它,但结果是一样的。结果表明,这段代码中存在非常明显的死锁。我已经重新设计了整个系统,以避免出现此问题,而不是添加额外的线程来处理锁定。您是否可以在定时循环中测试WqlEventQuery,例如每2-3秒测试一次,以查看Win32_DeviceChangeEvent是否真的显示在WMI中?之后,您可以尝试使用一些您知道会定期更改的内容(如Win32_LocalTime中的Select*)测试ManagementEventWatcher。您是否考虑过一个不同的查询,可能是基于以下查询的:?您是否查看了一些句柄是如何连接/断开的?