WPF检测设备变化

如果在构造函数中设置会出现为空

HwndSource source = PresentationSource.FromVisual(this) as HwndSource;

  此时 source = null,

所以就该放在加载事件中

void Main()
{
    var window = new Window
    {
        Width = 0,
        Height = 0,
        WindowStyle = WindowStyle.None,
        ShowInTaskbar = false,
        ShowActivated = false
    };
    window.Loaded += a_Loaded;
    window.Show();
}

void a_Loaded(object sender, EventArgs e)
{
    var s = (Window) sender;
    var source = PresentationSource.FromVisual(s);
     if (hwndSource != null)
                {
                    hwndSource.AddHook(newHwndSourceHook(USBDeviceChanged));
                }
    //...
    s.Close();
}

/// <summary>
/// 设备变更
/// </summary>

WM_DEVICECHANGE = 0x219,

/// <summary>
/// 设备树节点变更(新增或删除了设备)
/// </summary>
DBT_DEVNODES_CHANGED = 0x0007,

 

private IntPtr USBDeviceChanged(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handle)
{
  if (msg == WindowsMessage.WM_DEVICECHANGE.GetHashCode())
  {

     if (wParam.ToInt32() == WindowsMessage.DBT_DEVNODES_CHANGED.GetHashCode())

     DeviceUpdate();

  }

  return IntPtr.Zero;

}

 

 

posted @ 2023-02-14 13:48  stweily  阅读(103)  评论(0编辑  收藏  举报