2010-01-13 15 views
30

मैं एक क्लास लाइब्रेरी लिखने की कोशिश कर रहा हूं जो किसी डिवाइस को संलग्न या निकाला गया है, तो मुझे सूचित करने के लिए विंडोज संदेशों को पकड़ सकता है। आम तौर पर, विंडोज़ ऐप में ऐप मैं सिर्फ WndProc विधि को ओवरराइड करता हूं लेकिन इस मामले में WndProc विधि नहीं है। क्या कोई और तरीका है जिससे मैं संदेश प्राप्त कर सकता हूं?विंडोज़ फॉर्म के बिना प्लग और प्ले डिवाइस अधिसूचनाएं कैसे प्राप्त करें

उत्तर

38

आपको एक विंडो की आवश्यकता होगी, इसके आस-पास कोई रास्ता नहीं है। यहां एक नमूना कार्यान्वयन है। नोटिफिकेशन प्राप्त करने के लिए DeviceChangeNotifier.DeviceNotify ईवेंट के लिए इवेंट हैंडलर को कार्यान्वित करें। अपने प्रोग्राम की शुरुआत में DeviceChangeNotifier.Start() विधि को कॉल करें। अपने प्रोग्राम के अंत में DeviceChangeNotifier.Stop() पर कॉल करें। सावधान रहें कि डिवाइस थॉट इवेंट पृष्ठभूमि पृष्ठभूमि थ्रेड पर उठाया गया है, अपने कोड को थ्रेड-सुरक्षित रखने के लिए आवश्यकतानुसार लॉक करना सुनिश्चित करें।

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); 
    } 
} 
+1

+1 महान उदाहरण है, और nobugz सही है, तो आप एक खिड़की की जरूरत है। – SwDevMan81

+0

+1। अच्छा उदाहरण –

+0

मुझे लगता है कि आप इनवोक का उपयोग करते हैं। क्या यह काम करता है यदि प्रतिनिधि यूआई में नहीं है? –

5

मेरे पास एक काम कर रहे यूएसबी संचार वर्ग है जो किसी को रुचि रखने पर डिवाइस परिवर्तन अधिसूचना को थोड़ा अलग तरीके से लागू करता है। यह बहुत कॉम्पैक्ट है (टिप्पणियां w/o) और क्लाइंट में Threading या OnSourceInitialized और HwndHandler सामग्री पर निर्भर नहीं है। इसके अलावा, आपको उल्लिखित Form या विंडो की आवश्यकता नहीं है। कोई भी प्रकार जहां आप WndProc() ओवरराइड कर सकते हैं। मैं Control का उपयोग करता हूं।

नमूना में केवल अधिसूचना के लिए आवश्यक कोड शामिल है और कुछ भी नहीं। नमूना कोड सी ++/सीएलआई है और हालांकि मैं ब्रेवटी के लिए हेडर फाइलों में निष्पादन योग्य कोड डालने के अभ्यास की सदस्यता नहीं लेता हूं, मैं यहां ऐसा करता हूं।

#pragma once 

#include <Windows.h> // Declares required datatypes. 
#include <Dbt.h>  // Required for WM_DEVICECHANGE messages. 
#include <initguid.h> // Required for DEFINE_GUID definition (see below). 

namespace USBComms 
{ 
    using namespace System; 
    using namespace System::Runtime::InteropServices; 
    using namespace System::Windows; 
    using namespace System::Windows::Forms; 

    // This function is required for receieving WM_DEVICECHANGE messages. 
    // Note: name is remapped "RegisterDeviceNotificationUM" 
    [DllImport("user32.dll" , CharSet = CharSet::Unicode, EntryPoint="RegisterDeviceNotification")]     
    extern "C" HDEVNOTIFY WINAPI RegisterDeviceNotificationUM(
     HANDLE hRecipient, 
     LPVOID NotificationFilter, 
     DWORD Flags); 

    // Generic guid for usb devices (see e.g. http://msdn.microsoft.com/en-us/library/windows/hardware/ff545972%28v=vs.85%29.aspx). 
    // Note: GUIDs are device and OS specific and may require modification. Using the wrong guid will cause notification to fail. 
    // You may have to tinker with your device to find the appropriate GUID. "hid.dll" has a function `HidD_GetHidGuid' that returns 
    // "the device interfaceGUID for HIDClass devices" (see http://msdn.microsoft.com/en-us/library/windows/hardware/ff538924%28v=vs.85%29.aspx). 
    // However, testing revealed it does not always return a useful value. The GUID_DEVINTERFACE_USB_DEVICE value, defined as 
    // {A5DCBF10-6530-11D2-901F-00C04FB951ED}, has worked with cell phones, thumb drives, etc. For more info, see e.g. 
    // http://msdn.microsoft.com/en-us/library/windows/hardware/ff553426%28v=vs.85%29.aspx. 
    DEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED); 

    /// <summary> 
    /// Declare a delegate for the notification event handler. 
    /// </summary> 
    /// <param name="sender">The object where the event handler is attached.</param> 
    /// <param name="e">The event data.</param> 
    public delegate void NotificationEventHandler(Object^ sender, EventArgs^ e); 

    /// <summary> 
    /// Class that generetaes USB Device Change notification events. 
    /// </summary> 
    /// <remarks> 
    /// A Form is not necessary. Any type wherein you can override WndProc() can be used. 
    /// </remarks> 
    public ref class EventNotifier : public Control 
    { 
    private: 
     /// <summary> 
     /// Raises the NotificationEvent. 
     /// </summary> 
     /// <param name="e">The event data.</param> 
     void RaiseNotificationEvent(EventArgs^ e) { 
      NotificationEvent(this, e); 
     } 

    protected: 
     /// <summary> 
     /// Overrides the base class WndProc method. 
     /// </summary> 
     /// <param name="message">The Windows Message to process. </param> 
     /// <remarks> 
     /// This method receives Windows Messages (WM_xxxxxxxxxx) and 
     /// raises our NotificationEvent as appropriate. Here you should 
     /// add any message filtering (e.g. for the WM_DEVICECHANGE) and 
     /// preprocessing before raising the event (or not). 
     /// </remarks> 
     virtual void WndProc(Message% message) override { 
      if(message.Msg == WM_DEVICECHANGE) 
      { 
       RaiseNotificationEvent(EventArgs::Empty); 
      } 
      __super::WndProc(message); 
     } 

    public: 
     /// <summary> 
     /// Creates a new instance of the EventNotifier class. 
     /// </summary> 
     EventNotifier(void) { 
      RequestNotifications(this->Handle); // Register ourselves as the Windows Message processor. 
     } 

     /// <summary> 
     /// Registers an object, identified by the handle, for 
     /// Windows WM_DEVICECHANGE messages. 
     /// </summary> 
     /// <param name="handle">The object's handle.</param> 
     bool RequestNotifications(IntPtr handle) { 
      DEV_BROADCAST_DEVICEINTERFACE NotificationFilter; 

      ZeroMemory(&NotificationFilter, sizeof(NotificationFilter)); 
      NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; 
      NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); 
      NotificationFilter.dbcc_reserved = 0; 
      NotificationFilter.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE; 
      return RegisterDeviceNotificationUM((HANDLE)handle, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE) != NULL; 
     } 

     /// <summary> 
     /// Defines the notification event. 
     /// </summary> 
     virtual event NotificationEventHandler^ NotificationEvent; 
    }; 
} 

फिर, 'रिसीवर' (उद्देश्य यह है कि का सदस्य बनता है और हमारे NotificationEvent खपत) में, तुम सब करने की ज़रूरत है:

void Receiver::SomeFunction(void) 
{ 
    USBComms::EventNotifier usb = gcnew USBComms::EventNotifier(); 

    usb->NotificationEvent += gcnew USBComms::NotificationEventHandler(this, &Receiver::USBEvent); 
} 

void Receiver::USBEvent(Object^ sender, EventArgs^ e) 
{ 
    // Handle the event notification as appropriate. 
} 
+0

फॉर्म नियंत्रण और नियंत्रण से निकला है वैसे भी Win32 विंडो इंस्टेंस को लपेटता है। मैंने पाया है कि एकमात्र गैर-विंडो आधारित विधि प्रबंधनEventWatcher का उपयोग करना है। लेकिन ऐसा लगता है कि इसकी अपनी समस्याएं हैं। – Felix

0

Windows CE/विंडोज मोबाइल/SmartDevice परियोजनाओं में, मानक FormWndProc विधि पर ओवरराइड प्रदान नहीं करता है, लेकिन इसे Microsoft.WindowsCE.Forms.MessageWindow पर आधारित क्लास बनाने के द्वारा पूरा किया जा सकता है, एक ऐसा फॉर्म बनाने वाला एक कन्स्ट्रक्टर बनाकर, उस फॉर्म को स्थानीय चर में रखें ताकि उस फॉर्म पर एक विधि हो जब भी संदेश का पता चला जाता है कहा जाता है। उदाहरण के लिए यहां एक स्केल डाउन नमूना है। उम्मीद है कि यह सीई/विंडोज मोबाइल दुनिया में किसी के लिए सहायक है।

public class MsgWindow : Microsoft.WindowsCE.Forms.MessageWindow { 

    public const int WM_SER = 0x500; 
    public const int WM_SER_SCANDONE = WM_SER + 0; 

    frmMain msgform { get; set; } 

    public MsgWindow(frmMain msgform) { 
     this.msgform = msgform; 
    } 

    protected override void WndProc(ref Microsoft.WindowsCE.Forms.Message m) { 
     switch (m.Msg) { 
     case WM_SER_SCANDONE: 
      this.msgform.RespondToMessage(WM_SER_SCANDONE); 
      break; 
     default: 
      break; 
     } 
     base.WndProc(ref m); 
    } 

    } 

    public partial class frmMain : Form { 

    public frmMain() { 
     InitializeComponent(); 
    } 

    public void RespondToMessage(int nMsg) { 
     try { 
     switch (nMsg) { 
      case MsgWindow.WM_SER_SCANDONE: 
      // do something here based on the message 
      break; 
      default: 
      break; 
     } 
     } catch (Exception ex) { 
     MessageBox.Show(string.Format("{0} - {1}", ex.Message, ex.ToString()), "RespondToMessage() Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); 
     // throw; 
     } 
    } 

    } 
संबंधित मुद्दे