c# - How to receive Plug & Play device notifications without a windows form -


i trying write class library can catch windows messages notify me if device has been attached or removed. normally, in windows forms app override wndproc method there not wndproc method in case. there way can messages?

you'll need window, there's no way around that. here's sample implementation. implement event handler devicechangenotifier.devicenotify event notifications. call devicechangenotifier.start() method @ start of program. call devicechangenotifier.stop() @ end of program. beware devicenotify event raised on background thread, sure lock needed keep 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);   } } 

Comments

Popular posts from this blog

unicode - Are email addresses allowed to contain non-alphanumeric characters? -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

c++ - Convert big endian to little endian when reading from a binary file -