您的位置:首页 > 编程语言 > C#

C# USB Detection - winform and WPF

2010-12-23 14:41 429 查看
Win From Version:

代码

UsbDetector usbDetector;
public MainWindow()
{
InitializeComponent();
usbDetector = new UsbDetector();
usbDetector.StateChanged += new Lenovo.Common.Devices.UsbStateChangedEventHandler(usbDetector_StateChanged);

this.Loaded += new RoutedEventHandler(MainWindow_Loaded);

}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
WindowInteropHelper interop = new WindowInteropHelper(this);
HwndSource hwndSource = HwndSource.FromHwnd(interop.Handle);
HwndSourceHook hool = new HwndSourceHook(usbDetector.HwndHandler);
hwndSource.AddHook(hool); ;
usbDetector.RegisterDeviceNotification(interop.Handle);
}

void usbDetector_StateChanged(bool arrival)
{
if (arrival)
MessageBox.Show("add");
else
MessageBox.Show("removed");
}

In generally, the wParam should be DBT_DEVICEARRIVAL or DBT_DEVICEREMOVECOMPLETE, but some time , it keep be the wParam =7 (DBT_DEVNODES_CHANGED) and LParam = 0, that is that the usb driver isn't correctly installed.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: