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

查看:120
本文介绍了如何接收即插即放;播放设备通知没有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事件在后台线程提出,要确保锁定为需要保持你的code线程安全的。

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天全站免登陆