Exemple #1
0
        static IntPtr  RegisterDeviceNotification(IntPtr hwnd, Guid guid)
        {
            var notifyFilter = new NativeMethods.DEV_BROADCAST_DEVICEINTERFACE()
            {
                Size       = Marshal.SizeOf(typeof(NativeMethods.DEV_BROADCAST_DEVICEINTERFACE)),
                ClassGuid  = guid,
                DeviceType = NativeMethods.DBT_DEVTYP_DEVICEINTERFACE
            };
            var notifyHandle = NativeMethods.RegisterDeviceNotification(hwnd, ref notifyFilter, 0);

            RunAssert(notifyHandle != IntPtr.Zero, "HidSharp RegisterDeviceNotification failed.");
            return(notifyHandle);
        }
        protected override void Run(Action readyCallback)
        {
            const string className = "HidSharpDeviceMonitor";

            NativeMethods.WindowProc windowProc = DeviceMonitorWindowProc; GC.KeepAlive(windowProc);
            var wc = new NativeMethods.WNDCLASS()
            {
                ClassName = className, WindowProc = windowProc
            };

            RunAssert(0 != NativeMethods.RegisterClass(ref wc), "HidSharp RegisterClass failed.");

            var hwnd = NativeMethods.CreateWindowEx(0, className, className, 0,
                                                    NativeMethods.CW_USEDEFAULT, NativeMethods.CW_USEDEFAULT, NativeMethods.CW_USEDEFAULT, NativeMethods.CW_USEDEFAULT,
                                                    NativeMethods.HWND_MESSAGE,
                                                    IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

            RunAssert(hwnd != IntPtr.Zero, "HidSharp CreateWindow failed.");

            var notifyFilter = new NativeMethods.DEV_BROADCAST_DEVICEINTERFACE()
            {
                Size       = Marshal.SizeOf(typeof(NativeMethods.DEV_BROADCAST_DEVICEINTERFACE)),
                ClassGuid  = NativeMethods.HidD_GetHidGuid(),
                DeviceType = NativeMethods.DBT_DEVTYP_DEVICEINTERFACE
            };
            var notifyHandle = NativeMethods.RegisterDeviceNotification(hwnd, ref notifyFilter, 0);

            RunAssert(notifyHandle != IntPtr.Zero, "HidSharp RegisterDeviceNotification failed.");

            readyCallback();

            NativeMethods.MSG msg;
            while (true)
            {
                int result = NativeMethods.GetMessage(out msg, hwnd, 0, 0);
                if (result == 0 || result == -1)
                {
                    break;
                }

                NativeMethods.TranslateMessage(ref msg);
                NativeMethods.DispatchMessage(ref msg);
            }

            RunAssert(NativeMethods.UnregisterDeviceNotification(notifyHandle), "HidSharp UnregisterDeviceNotification failed.");
            RunAssert(NativeMethods.DestroyWindow(hwnd), "HidSharp DestroyWindow failed.");
            RunAssert(NativeMethods.UnregisterClass(className, IntPtr.Zero), "HidSharp UnregisterClass failed.");
        }