如何知道WPF中的设备是插入还是拔出?
我使用以下代码检测设备更改:
private void OnSourceInitialized(object sender, EventArgs e)
{
IntPtr windowHandle = (new WindowInteropHelper(this)).Handle;
HwndSource src = HwndSource.FromHwnd(windowHandle);
src.AddHook(new HwndSourceHook(WndProc));
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// Handle WM_DEVICECHANGE...
if (msg == 0x219)
{
InitHead();
}
return IntPtr.Zero;
}
谢谢。
编辑:
我做了以下操作,仍然没有工作:
if (msg == 0x0219)
{
switch (wParam.ToInt32())
{
case 0x8000:
{
InitHead();
}
break;
}
}
答案 0 :(得分:3)
要检测设备是否已插入,我们将钩子添加到我们的Window_Loaded
方法中,如下所示
HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(new HwndSourceHook(this.WndProc));
处理程序如下所示:
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == 0x0219 && (int)wParam == 0x8000) // 0x8000 is DBT_DEVICEARRIVAL
{
ProcessConnected();
}
return IntPtr.Zero;
}
不幸的是,当设备被拔出时,没有触发任何DBT_DEVICE常量,而是在尝试从Windows弹出设备时调用它们。