如何接收即插即用播放没有 Windows 窗体的设备通知 [英] How to receive Plug & Play device notifications without a windows form

查看:26
本文介绍了如何接收即插即用播放没有 Windows 窗体的设备通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个类库,它可以捕获 Windows 消息以在设备已连接或删除时通知我.通常,在 Windows 窗体应用程序中,我只会覆盖 WndProc 方法,但在这种情况下没有 WndProc 方法.还有其他方法可以获取消息吗?

I am trying to write a class library that can catch the windows messages to notify me if a device has been attached or removed. Normally, in a windows forms app I would just override the WndProc method but there is not WndProc method in this case. Is there another way I can get the messages?

推荐答案

你需要一个窗口,没有办法解决这个问题.这是一个示例实现.为 DeviceChangeNotifier.DeviceNotify 事件实现一个事件处理程序以获取通知.在程序开始时调用 DeviceChangeNotifier.Start() 方法.在程序结束时调用 DeviceChangeNotifier.Stop().请注意 DeviceNotify 事件是在后台线程上引发的,请务必根据需要锁定以确保您的代码线程安全.

You'll need a window, there's no way around that. Here's a sample implementation. Implement an event handler for the DeviceChangeNotifier.DeviceNotify event to get notifications. Call the DeviceChangeNotifier.Start() method at the start of your program. Call DeviceChangeNotifier.Stop() at the end of your program. Beware that the DeviceNotify event is raised on a background thread, be sure to lock as needed to keep your code thread-safe.

using System;
using System.Windows.Forms;
using System.Threading;

class DeviceChangeNotifier : Form {
  public delegate void DeviceNotifyDelegate(Message msg);
  public static event DeviceNotifyDelegate DeviceNotify;
  private static DeviceChangeNotifier mInstance;

  public static void Start() {
    Thread t = new Thread(runForm);
    t.SetApartmentState(ApartmentState.STA);
    t.IsBackground = true;
    t.Start();
  }
  public static void Stop() {
    if (mInstance == null) throw new InvalidOperationException("Notifier not started");
    DeviceNotify = null;
    mInstance.Invoke(new MethodInvoker(mInstance.endForm));
  }
  private static void runForm() {
    Application.Run(new DeviceChangeNotifier());
  }

  private void endForm() {
    this.Close();
  }
  protected override void SetVisibleCore(bool value) {
    // Prevent window getting visible
    if (mInstance == null) CreateHandle();
    mInstance = this;
    value = false;
    base.SetVisibleCore(value);
  }
  protected override void WndProc(ref Message m) {
    // Trap WM_DEVICECHANGE
    if (m.Msg == 0x219) {
      DeviceNotifyDelegate handler = DeviceNotify;
      if (handler != null) handler(m);
    }
    base.WndProc(ref m);
  }
}

这篇关于如何接收即插即用播放没有 Windows 窗体的设备通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆