示例#1
0
    /// <summary>
    /// Registers a window to receive notifications when USB devices are plugged or unplugged.
    /// </summary>
    /// <param name="windowHandle">Handle to the window receiving notifications.</param>
    public static void RegisterUsbDeviceNotification(IntPtr windowHandle)
    {
        DevBroadcastDeviceinterface0 dbi0 = new DevBroadcastDeviceinterface0
        {
            DeviceType = DBT_DEVTYP_DEVICEINTERFACE,
            Reserved   = 0,
            ClassGuid  = GuidDevinterfaceUSBDevice,
            Name       = 0
        };

        dbi0.Size = Marshal.SizeOf(dbi0);
        IntPtr buffer = Marshal.AllocHGlobal(dbi0.Size);

        Marshal.StructureToPtr(dbi0, buffer, true);

        notificationHandle = RegisterDeviceNotification(windowHandle, buffer, 0);
    }
示例#2
0
    public static DevBroadcastDeviceinterface GetDevBroadcastDeviceinterface(Message m)
    {
        DevBroadcastHdr hdr = GetDevBroadcastHdr(m);

        if (hdr.DeviceType == DBT_DEVTYP_DEVICEINTERFACE)
        {
            DevBroadcastDeviceinterface0 dbi0 = (DevBroadcastDeviceinterface0)m.GetLParam(typeof(DevBroadcastDeviceinterface0));
            DevBroadcastDeviceinterface  dbi  = new DevBroadcastDeviceinterface()
            {
                DeviceType = dbi0.DeviceType, ClassGuid = dbi0.ClassGuid
            };
            Byte[] bytes = new Byte[hdr.Size];
            Marshal.Copy((IntPtr)m.LParam, bytes, 0, hdr.Size);
            int offset = Marshal.SizeOf(dbi0) - 2;
            dbi.Name = System.Text.Encoding.Unicode.GetString(bytes, offset, bytes.Length - offset);
            return(dbi);
        }
        return(new DevBroadcastDeviceinterface());
    }