Even though you are using WPF, you can still intercept WM_DEVICECHANGE
. You could either attach to an existing window procedure using WPF callback methods, or you could use a System.Windows.Forms.NativeWindow
(my preferred method, more control and easier, but you do need to add a reference to System.Windows.Forms.dll)
// in your window's code behind
private static int WM_DEVICECHANGE = 0x0219;
protected override void OnSourceInitialized(EventArgs e)
{
WindowInteropHelper helper = new WindowInteropHelper(this);
SystemEventIntercept intercept = new SystemEventIntercept(helper.Handle);
base.OnSourceInitialized(e);
}
class SystemEventIntercept : System.Windows.Forms.NativeWindow
{
public SystemEventIntercept(IntPtr handle)
{
this.AssignHandle(handle);
}
protected override void WndProc(ref Winforms.Message m)
{
if (m.Msg == WM_DEVICECHANGE)
{
// do something
}
base.WndProc(ref m);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…