我需要检测USB设备更改事件并将更改更新为WPF窗口。这是我的代码。
public MainWindow()
{
InitializeComponent();
SourceInitialized += (sender, e) =>
{
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
source.AddHook(WndProc);
};
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == 0x219) // Device Changed
{
UpdateSerialPortDict();
}
return IntPtr.Zero;
}
private void UpdateSerialPortDict()
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"^[\S\s]+\((COM([0-9])+)\)$");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity"))
{
foreach (ManagementObject obj in searcher.Get())
{
if ((string)obj["PNPClass"] == "Ports")
{
string key = obj["Name"] as string;
var mat = reg.Match(key);
if (mat.Success)
{
var val = mat.Groups[1].Value;
_comDictionary.Add(key, val);
}
}
}
}
}
调用searcher.Get()
时程序将崩溃。如果我使用Button来触发UpdateSerialPortDict()
,它可以正常工作。但我会通过检测设备更改事件自动更新。
答案 0 :(得分:2)
尝试使用调度程序:
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == 0x219) // Device Changed
{
Dispatcher.BeginInvoke(new Action(() => UpdateSerialPortDict()),
System.Windows.Threading.DispatcherPriority.Background);
}
return IntPtr.Zero;
}