예제 #1
0
        public static bool TryPtrToDeviceInfo(IntPtr handle, out UsbDeviceInfo deviceInfo)
        {
            bool Result = false;

            deviceInfo = null;
            try
            {
                DEV_BROADCAST_HDR header = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(handle, typeof(DEV_BROADCAST_HDR));

                if (header.DeviceType == DBT.DEVTYP_DEVICEINTERFACE)
                {
                    DEV_BROADCAST_DEVICEINTERFACE devInterface = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(handle, typeof(DEV_BROADCAST_DEVICEINTERFACE));
                    var broadcastName = devInterface.Name;
                    var friendlyName  = GetDeviceFriendlyName(broadcastName);

                    deviceInfo = new UsbDeviceInfo
                    {
                        Name         = broadcastName,
                        ClassGuid    = devInterface.ClassGuid,
                        FriendlyName = friendlyName,
                    };

                    Result = true;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(Result);
        }
예제 #2
0
        ///  <summary>
        ///  Compares two device path names. Used to find out if the device name 
        ///  of a recently attached or removed device matches the name of a 
        ///  device the application is communicating with.
        ///  </summary>
        ///  
        ///  <param name="m"> a WM_DEVICECHANGE message. A call to RegisterDeviceNotification
        ///  causes WM_DEVICECHANGE messages to be passed to an OnDeviceChange routine.. </param>
        ///  <param name="mydevicePathName"> a device pathname returned by 
        ///  SetupDiGetDeviceInterfaceDetail in an SP_DEVICE_INTERFACE_DETAIL_DATA structure. </param>
        ///  
        ///  <returns>
        ///  True if the names match, False if not.
        ///  </returns>
        ///  
        internal Boolean DeviceNameMatch(Message m, String mydevicePathName)
        {
            Int32 stringSize;

            try
            {
                DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
                DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();

                // The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure.

                Marshal.PtrToStructure(m.LParam, devBroadcastHeader);

                if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
                {
                    // The dbch_devicetype parameter indicates that the event applies to a device interface.
                    // So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure,
                    // which begins with a DEV_BROADCAST_HDR.

                    // Obtain the number of characters in dbch_name by subtracting the 32 bytes
                    // in the strucutre that are not part of dbch_name and dividing by 2 because there are
                    // 2 bytes per character.

                    stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);

                    // The dbcc_name parameter of devBroadcastDeviceInterface contains the device name.
                    // Trim dbcc_name to match the size of the String.

                    devBroadcastDeviceInterface.dbcc_name = new Char[stringSize + 1];

                    // Marshal data from the unmanaged block pointed to by m.LParam
                    // to the managed object devBroadcastDeviceInterface.

                    Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface);

                    // Store the device name in a String.

                    String DeviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);

                    // Compare the name of the newly attached device with the name of the device
                    // the application is accessing (mydevicePathName).
                    // Set ignorecase True.

                    if ((String.Compare(DeviceNameString, mydevicePathName, true) == 0))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return false;
        }
        /// <summary>
        /// Handles the window message when a drive change is in progress or finished
        /// </summary>
        /// <param name="msg">Window message</param>
        /// <returns>true, if the message was handled</returns>
        public static bool HandleDeviceChangedMessage(Message msg)
        {
            DEV_BROADCAST_HDR    hdr = new DEV_BROADCAST_HDR();
            DEV_BROADCAST_VOLUME vol = new DEV_BROADCAST_VOLUME();

            try
            {
                if (msg.WParam.ToInt32() == DBT_DEVICEARRIVAL)
                {
                    // new device
                    hdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(msg.LParam, hdr.GetType());
                    if (hdr.devicetype == DBT_DEVTYPE_VOLUME)
                    {
                        vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(msg.LParam, vol.GetType());
                        return(DeviceNew(vol));
                    }
                }
                else if (msg.WParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE)
                {
                    // device remove
                    hdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(msg.LParam, hdr.GetType());
                    if (hdr.devicetype == DBT_DEVTYPE_VOLUME)
                    {
                        vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(msg.LParam, vol.GetType());
                        return(DeviceRemoved(vol));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error in handling device changed message: {0}", ex);
            }
            return(false);
        }
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WndProMsgConst.WM_DEVICECHANGE)
            {
                DEV_BROADCAST_HDR lpdb = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                switch (m.WParam.ToInt32())
                {
                case WndProMsgConst.DBT_DEVICEARRIVAL:
                    if (lpdb.dbch_devicetype == WndProMsgConst.DBT_DEVTYP_VOLUME)
                    {
                        DEV_BROADCAST_VOLUME lpdbv = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                        int a = lpdbv.dbcv_flags & WndProMsgConst.DBTF_MEDIA;
                        if ((lpdbv.dbcv_flags & WndProMsgConst.DBTF_MEDIA) == WndProMsgConst.DBTF_MEDIA)
                        {
                            System.Windows.Forms.MessageBox.Show(DriveMaskToLetter(lpdbv.dbcv_unitmask).ToString());
                        }
                    }
                    break;

                case WndProMsgConst.DBT_DEVICEREMOVECOMPLETE:
                    if (lpdb.dbch_devicetype == WndProMsgConst.DBT_DEVTYP_VOLUME)
                    {
                        DEV_BROADCAST_VOLUME lpdbv = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                        int a = lpdbv.dbcv_flags & WndProMsgConst.DBTF_MEDIA;
                        if ((lpdbv.dbcv_flags & WndProMsgConst.DBTF_MEDIA) == WndProMsgConst.DBTF_MEDIA)
                        {
                            System.Windows.Forms.MessageBox.Show(DriveMaskToLetter(lpdbv.dbcv_unitmask).ToString());
                        }
                    }
                    break;
                }
            }

            base.WndProc(ref m);
        }
예제 #5
0
        // Static routine to parse out the device type from the IntPtr received in WndProc
        public bool CheckEventDetails(IntPtr pReason, IntPtr pHdr)
        {
            int iValue = pReason.ToInt32();

            // Check the event type
            if (iValue != DBT_DEVICEREMOVECOMPLETE && iValue != DBT_DEVICEARRIVAL)
            {
                return(false);
            }

            // Do we have device details yet?
            if (pHdr == IntPtr.Zero)
            {
                return(false);
            }

            // Parse the first chunk
            DEV_BROADCAST_HDR pBH = new DEV_BROADCAST_HDR();

            Marshal.PtrToStructure(pHdr, pBH);

            // Check the device type
            if (pBH.dbch_devicetype != DBT_DEVTYP_DEVICEINTERFACE)
            {
                return(false);
            }

            // Only parse this if the right device type
            DEV_BROADCAST_DEVICEINTERFACE pDI = new DEV_BROADCAST_DEVICEINTERFACE();

            Marshal.PtrToStructure(pHdr, pDI);

            return(pDI.dbcc_classguid == m_Category);
        }
예제 #6
0
        ///  <summary>
        ///  Compares two device path names. Used to find out if the device name
        ///  of a recently attached or removed device matches the name of a
        ///  device the application is communicating with.
        ///  </summary>
        ///
        ///  <param name="m"> a WM_DEVICECHANGE message. A call to RegisterDeviceNotification
        ///  causes WM_DEVICECHANGE messages to be passed to an OnDeviceChange routine.. </param>
        ///  <param name="mydevicePathName"> a device pathname returned by
        ///  SetupDiGetDeviceInterfaceDetail in an SP_DEVICE_INTERFACE_DETAIL_DATA structure. </param>
        ///
        ///  <returns>
        ///  True if the names match, False if not.
        ///  </returns>
        ///
        internal Boolean DeviceNameMatch(Message m, String mydevicePathName)
        {
            Int32 stringSize;

            try
            {
                DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
                DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();

                // The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure.

                Marshal.PtrToStructure(m.LParam, devBroadcastHeader);

                if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
                {
                    // The dbch_devicetype parameter indicates that the event applies to a device interface.
                    // So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure,
                    // which begins with a DEV_BROADCAST_HDR.

                    // Obtain the number of characters in dbch_name by subtracting the 32 bytes
                    // in the strucutre that are not part of dbch_name and dividing by 2 because there are
                    // 2 bytes per character.

                    stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);

                    // The dbcc_name parameter of devBroadcastDeviceInterface contains the device name.
                    // Trim dbcc_name to match the size of the String.

                    devBroadcastDeviceInterface.dbcc_name = new Char[stringSize + 1];

                    // Marshal data from the unmanaged block pointed to by m.LParam
                    // to the managed object devBroadcastDeviceInterface.

                    Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface);

                    // Store the device name in a String.

                    String DeviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);

                    // Compare the name of the newly attached device with the name of the device
                    // the application is accessing (mydevicePathName).
                    // Set ignorecase True.

                    if ((String.Compare(DeviceNameString, mydevicePathName, true) == 0))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return(false);
        }
예제 #7
0
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == (int)WM_DEVICECHANGE)
            {
                if (m.LParam != IntPtr.Zero)
                {
                    DEV_BROADCAST_HDR BroadcastHdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                    if (BroadcastHdr.dbch_devicetype == DeviceType.DBT_DEVTYP_VOLUME)
                    {
                        DEV_BROADCAST_VOLUME VolumeHdr = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                        if (VolumeHdr.dbcv_flags != VolumeType.DBTF_NET)
                        {
                            switch ((WmDeviceChangeEvent)m.WParam.ToInt32())
                            {
                            case WmDeviceChangeEvent.DBT_DEVICEARRIVAL:
                                if (DeviceArrived != null)
                                {
                                    DeviceArrived(this, new DeviceWindowEventArgs(VolumeHdr.dbcv_unitmask));
                                }
                                break;

                            case WmDeviceChangeEvent.DBT_DEVICEREMOVECOMPLETE:
                                if (DeviceRemoved != null)
                                {
                                    DeviceRemoved(this, new DeviceWindowEventArgs(VolumeHdr.dbcv_unitmask));
                                }
                                break;
                            }
                        }
                    }
                }
            }

            base.WndProc(ref m);
        }
예제 #8
0
        /// <summary>
        /// 检测USB串口的拔插
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICE_CHANGE) // 捕获USB设备的拔出消息WM_DEVICECHANGE
            {
                switch (m.WParam.ToInt32())
                {
                case DBT_DEVICE_REMOVE_COMPLETE:     // USB拔出
                    DEV_BROADCAST_HDR dbhd = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                    if (dbhd.dbch_devicetype == DBT_DEVTYP_PORT)
                    {
                        string portName = Marshal.PtrToStringUni((IntPtr)(m.LParam.ToInt32() + Marshal.SizeOf(typeof(DEV_BROADCAST_PORT_Fixed))));
                        //MessageBox.Show(portName+" 已拔出");
                        Display();
                    }

                    break;

                case DBT_DEVICEARRIVAL:     // USB插入获取对应串口名称
                    DEV_BROADCAST_HDR dbhdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                    if (dbhdr.dbch_devicetype == DBT_DEVTYP_PORT)
                    {
                        string portName = Marshal.PtrToStringUni((IntPtr)(m.LParam.ToInt32() + Marshal.SizeOf(typeof(DEV_BROADCAST_PORT_Fixed))));
                        //MessageBox.Show(portName + " 已插入");
                        Display();
                    }
                    break;
                }
            }
            base.WndProc(ref m);
        }
예제 #9
0
        IntPtr MessageHook(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
        {
            switch ((WM)msg)
            {
            case WM.DEVICECHANGE:
                switch ((DBT)wparam)
                {
                case DBT.DEVICEARRIVAL:
                case DBT.DEVICEREMOVECOMPLETE:
                    var header = new DEV_BROADCAST_HDR();
                    Marshal.PtrToStructure(lparam, header);

                    if (header.dbcv_devicetype == DBT_DEVTYP.VOLUME)
                    {
                        var lpdbv = new DEV_BROADCAST_VOLUME();
                        Marshal.PtrToStructure(lparam, lpdbv);

                        if ((lpdbv.dbcv_flags & DBTF.MEDIA) != 0)
                        {
                            StartRefreshOpticalDrives();
                        }
                    }
                    break;
                }
                break;
            }
            return(IntPtr.Zero);
        }
예제 #10
0
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICECHANGE && m.WParam.ToInt32() == DBT_DEVICEARRIVAL)
            {
                DEV_BROADCAST_HDR DeviceInfo = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                if (DeviceInfo.dbch_devicetype == DBT_DEVTYP_VOLUME)
                {
                    DEV_BROADCAST_VOLUME Volume = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                    char DriveLetter            = GetDriveLetterFromMask(Volume.dbcv_unitmask);
                    if (DriveLetter == this.Mounter.DriveLetter)
                    {
                        if (this.Mounter.Silent)
                        {
                            this.Mounter.Silent = false;
                        }
                        else
                        {
                            this.Mounter.ExploreDrive(null, null);
                        }
                    }
                }
            }

            base.WndProc(ref m);
        }
예제 #11
0
        /// <summary>
        /// isNotificationForTargetDevice - Compares the target devices pathname against the
        /// pathname of the device which caused the event message
        /// </summary>
        private Boolean isNotificationForTargetDevice(Message m)
            {
            Int32 stringSize;

            try
                {
                DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
                DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();

                Marshal.PtrToStructure(m.LParam, devBroadcastHeader);

                // Is the notification event concerning a device interface?
                if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
                    {
                    // Get the device path name of the affected device
                    stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);    
                    devBroadcastDeviceInterface.dbcc_name = new Char[stringSize + 1];
                    Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface);
                    String deviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);

                    // Compare the device name with our target device's pathname (strings are moved to lower case
                    // using en-US to ensure case insensitivity accross different regions)
                    if ((String.Compare(deviceNameString.ToLower(new System.Globalization.CultureInfo("en-US")),
                        deviceInformation.devicePathName.ToLower(new System.Globalization.CultureInfo("en-US")), true) == 0)) return true;
                    else return false;
                    }
                }
            catch (Exception)
                {
                Debug.WriteLine("usbGenericHidCommunication:isNotificationForTargetDevice() -> EXCEPTION: An unknown exception has occured!");
                return false;
                }
            return false;
            }
예제 #12
0
        private void OnDeviceChange(ref Message m)
        {
            if (m.LParam.ToInt32() != 0)
            {
                EventHandler <DeviceNotifyEventArgs> temp = OnDeviceNotify;
                if (!ReferenceEquals(temp, null))
                {
                    DeviceNotifyEventArgs args;
                    DEV_BROADCAST_HDR     hdr = new DEV_BROADCAST_HDR();
                    Marshal.PtrToStructure(m.LParam, hdr);
                    switch (hdr.dbch_DeviceType)
                    {
                    case DeviceType.PORT:
                    case DeviceType.VOLUME:
                    case DeviceType.DEVICEINTERFACE:
                        args = new DeviceNotifyEventArgs(hdr, m.LParam, (EventType)m.WParam.ToInt32());
                        break;

                    default:
                        args = null;
                        break;
                    }

                    if (!ReferenceEquals(args, null))
                    {
                        temp(this, args);
                    }
                }
            }
        }
예제 #13
0
            protected override void WndProc(ref Message m)
            {
                IntPtr changeType = (IntPtr)m.WParam;

                if (m.Msg == WM_DEVICECHANGE)
                {
                    if (changeType == DBT_DEVICEARRIVAL)
                    {
                        DEV_BROADCAST_HDR header = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));

                        if (header.DeviceType == DBT_DEVTYP_PORT)
                        {
                            string portName = Marshal.PtrToStringAuto((IntPtr)((long)m.LParam + 12));
                            Log.Info("Port {0} was added", portName);

                            if (portName.StartsWith("COM"))
                            {
                                int port = Convert.ToInt32(portName.Substring(3));

                                // Notify listeners
                                if (PortAdded != null)
                                {
                                    PortAdded(this, new PortAddedEventArgs(port));
                                }
                            }
                        }
                    }
                }

                base.WndProc(ref m);
            }
예제 #14
0
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICECHANGE)
            {
                if (m.WParam.ToInt32() == DBT_DEVICEARRIVAL)
                {
                    // la clé à ete branchée
                    DEV_BROADCAST_HDR hdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));

                    // ok, le device pluggé est un volume (aussi appelé 'périphérique de stockage de masse')...
                    if (hdr.dbch_devicetype == DBT_DEVTYP_VOLUME)
                    {
                        // ... et donc on recréé une structure, a partir du même pointeur de structure "générique",
                        // une structure un poil plus spécifique
                        DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                        // le champs dbcv_unitmask contient la ou les lettres de lecteur du ou des devices qui viennent d'etre pluggé
                        // MSDN nous dit que si le bit 0 est à 1 alors le lecteur est a:, si le bit 1 est à 1 alors le lecteur est b:
                        // et ainsi de suite
                        uint mask = vol.dbcv_unitmask;
                        // recupèration des lettres de lecteurs
                        char[] letters = MaskDepioteur(mask);

                        // mise à jour de l'IHM pour notifier nos petits yeux tout content :)
                        //message = string.Format("USB key plugged on drive {0}:", letters[0].ToString().ToUpper());
                        string verif = letters[0].ToString().ToUpper() + ":\\texto.txt";
                        if (File.Exists(verif))
                        {
                            DialogResult dialogResult = MessageBox.Show("Voulez vous creer un nouveau profil archimed ?", "DETECTION D'UNE CLE ARCHIMEDE", MessageBoxButtons.YesNo);
                            if (dialogResult == DialogResult.Yes)
                            {
                                groupBox1.Visible   = true;
                                inserer_svp.Visible = false;
                                lbl_info.Visible    = false;
                            }
                            else if (dialogResult == DialogResult.No)
                            {
                                // a analyser
                            }
                        }

                        /*else
                         * {
                         *  MessageBox.Show("Ceci n'est pas un dispositif ARCHIMED");
                         * }*/
                    }
                }
                // le device vient d'etre retirer bourrinement ou proprement
                // (ce message intervient même quand on défait la clef softwarement mais qu'elle reste physiquement branché)
                else if (m.WParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE)
                {
                    // device removed

                    // mise à jour de l'IHM
                    message = "USB key unplugged";
                    //MessageBox.Show(message);
                }
            }
            // laissons notre fenêtre faire tout de même son boulot
            base.WndProc(ref m);
        }
예제 #15
0
        public static void AddHook(Sidebar window)
        {
            if (IsHooked)
            {
                return;
            }

            IsHooked = true;

            DEV_BROADCAST_HDR _data = new DEV_BROADCAST_HDR();

            _data.dbch_size       = Marshal.SizeOf(_data);
            _data.dbch_devicetype = DBCH_DEVICETYPE.DBT_DEVTYP_DEVICEINTERFACE;

            IntPtr _buffer = Marshal.AllocHGlobal(_data.dbch_size);

            Marshal.StructureToPtr(_data, _buffer, true);

            IntPtr _hwnd = new WindowInteropHelper(window).Handle;

            NativeMethods.RegisterDeviceNotification(
                _hwnd,
                _buffer,
                FLAGS.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES
                );

            window.HwndSource.AddHook(DeviceHook);
        }
예제 #16
0
        private static void DoDevTypPort(ref Message m, ref String text, ref DEV_BROADCAST_HDR hdr)
        {
#if false == false
            text += "Port: ";
            //DEV_BROADCAST_PORT hdrPort = (DEV_BROADCAST_PORT)m.GetLParam(typeof(DEV_BROADCAST_PORT));
            const int OffsetOfStringMember = 12; // ints not pointers, so fixed size.
            System.Diagnostics.Debug.Assert(OffsetOfStringMember
                                            == Marshal.OffsetOf(typeof(DEV_BROADCAST_PORT), "____dbcp_name").ToInt64());
            int    cbSpaceForString = hdr.dbch_size - OffsetOfStringMember;
            String str;
            if (cbSpaceForString > 0)
            {
                Int64  startPtrXX = OffsetOfStringMember + m.LParam.ToInt64();
                IntPtr startPtr   = (IntPtr)startPtrXX;
                // We won't use the length parameter in method PtrToStringUni as the
                // string we have here is null-terminated and often has trailing nulls
                // also, using the length overload would force their inclusion.
                str = System.Runtime.InteropServices.Marshal.PtrToStringUni(startPtr);
            }
            else
            {
                str = null;
            }
            text += str;
#endif
        }
예제 #17
0
        private void OnWmDeviceChange(UIntPtr wParam, IntPtr lParam)
        {
            DEV_BROADCAST_HDR dbh = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(lParam, typeof(DEV_BROADCAST_HDR));

            if (dbh.dbch_devicetype != DBT_DEVTYP_DEVICEINTERFACE)
            {
                return;
            }

            DEV_BROADCAST_DEVICEINTERFACE dbi = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(lParam, typeof(DEV_BROADCAST_DEVICEINTERFACE));

            UInt32 eventType = wParam.ToUInt32();

            if (DBT_DEVICEARRIVAL == eventType)
            {
                if (this.DeviceConnected != null)
                {
                    this.DeviceConnected(this, new DeviceManagementNotificationsEventArgs(true, dbi.dbcc_classguid, dbi.dbcc_name));
                }
            }
            else if (DBT_DEVICEREMOVECOMPLETE == eventType)
            {
                if (this.DeviceDisconnected != null)
                {
                    this.DeviceDisconnected(this, new DeviceManagementNotificationsEventArgs(false, dbi.dbcc_classguid, dbi.dbcc_name));
                }
            }
        }
예제 #18
0
        protected override void WndProc(ref Message m)
        {
            try
            {
                if (m.Msg == m_clsRegHidEvent.WM_DEVICECHANGE)
                {
                    if (m.WParam.ToInt32() == m_clsRegHidEvent.DBT_DEVICE_ARRIVAL ||
                        m.WParam.ToInt32() == m_clsRegHidEvent.DBT_DEVICE_REMOVE_COMPLETE)
                    {
                        DEV_BROADCAST_DEVICE_INTERFACE_2 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICE_INTERFACE_2();
                        DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();
                        devBroadcastDeviceInterface.dbcc_classguid = new Byte[1];
                        devBroadcastDeviceInterface.dbcc_name      = new Char[1];
                        Marshal.PtrToStructure(m.LParam, devBroadcastHeader);
                        if (devBroadcastHeader.dbcc_deviceType == m_clsRegHidEvent.DBT_DEVTYP_DEVICE_INTERFACE)
                        {
                            Int32 stringSize = Convert.ToInt32((devBroadcastHeader.dbcc_size - 32) / 2);
                            Array.Resize(ref devBroadcastDeviceInterface.dbcc_name, stringSize);
                            Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface);
                            HidArribval(m.WParam.ToInt32(), devBroadcastDeviceInterface.dbcc_name);
                        }
                    }
                }

                base.WndProc(ref m);
            }//try
            catch (Exception ex)
            {
                base.WndProc(ref m);
                MessageBox.Show(ex.Message);
            }
        }
예제 #19
0
    /// <summary>
    /// Handles the window message when a drive change is in progress or finished
    /// </summary>
    /// <param name="msg">Window message</param>
    /// <returns>true, if the message was handled</returns>
    public static bool HandleDeviceChangedMessage(Message msg)
    {
      DEV_BROADCAST_HDR hdr = new DEV_BROADCAST_HDR();
      DEV_BROADCAST_VOLUME vol = new DEV_BROADCAST_VOLUME();

      try
      {
        if (msg.WParam.ToInt32() == DBT_DEVICEARRIVAL)
        {
          // new device
          hdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(msg.LParam, hdr.GetType());
          if (hdr.devicetype == DBT_DEVTYPE_VOLUME)
          {
            vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(msg.LParam, vol.GetType());
            return DeviceNew(vol);
          }
        }
        else if (msg.WParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE)
        {
          // device remove
          hdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(msg.LParam, hdr.GetType());
          if (hdr.devicetype == DBT_DEVTYPE_VOLUME)
          {
            vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(msg.LParam, vol.GetType());
            return DeviceRemoved(vol);
          }
        }
      }
      catch (Exception ex)
      {
        Log.Error("Error in handling device changed message: {0}", ex);
      }
      return false;
    }
예제 #20
0
        // Get device name from notification message.
        // Also checks checkGuid with the GUID from the message to check the notification
        // is for a relevant device. Other messages might be received.
        public static string GetNotifyMessageDeviceName(IntPtr pDevBroadcastHeader, Guid checkGuid)
        {
            int stringSize;

            DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
            DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();

            // The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure.

            Marshal.PtrToStructure(pDevBroadcastHeader, devBroadcastHeader);

            if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
            {
                // The dbch_devicetype parameter indicates that the event applies to a device interface.
                // So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure,
                // which begins with a DEV_BROADCAST_HDR.

                // Obtain the number of characters in dbch_name by subtracting the 32 bytes
                // in the strucutre that are not part of dbch_name and dividing by 2 because there are
                // 2 bytes per character.

                stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);

                // The dbcc_name parameter of devBroadcastDeviceInterface contains the device name.
                // Trim dbcc_name to match the size of the String.

                devBroadcastDeviceInterface.dbcc_name = new char[stringSize + 1];

                // Marshal data from the unmanaged block pointed to by m.LParam
                // to the managed object devBroadcastDeviceInterface.

                Marshal.PtrToStructure(pDevBroadcastHeader, devBroadcastDeviceInterface);

                // Check if message is for the GUID
                if (devBroadcastDeviceInterface.dbcc_classguid != checkGuid)
                {
                    return(null);
                }

                // Store the device name in a String.
                string deviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);

                return(deviceNameString);
            }
            else if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_VOLUME))
            {
                DEV_BROADCAST_VOLUME vol = new DEV_BROADCAST_VOLUME();
                Marshal.PtrToStructure(pDevBroadcastHeader, vol);
                Int32 Mask     = vol.dbcv_unitmask;
                Int32 DriveInt = Convert.ToInt32('A') - 1;
                do
                {
                    Mask /= 2;
                    DriveInt++;
                }while (Mask > 0);
                return(@"\\.\" + Convert.ToChar(DriveInt) + ":");
            }
            return(null);
        }
예제 #21
0
 private DEV_BROADCAST_HANDLE__withData(int weAreForPinvoke)
 {
     this.header          = new DEV_BROADCAST_HDR();
     this.dbch_handle     = IntPtr.Zero;
     this.dbch_hdevnotify = IntPtr.Zero;
     this.dbch_eventguid  = Guid.Empty;
     this.dbch_nameoffset = this.dbch_nameoffset = 0;
     this.dbch_data__0    = this.dbch_data__0 = 0;
 }
예제 #22
0
        /// <summary>
        /// 检测USB串口的拔插
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICE_CHANGE)        // 捕获USB设备的拔出消息WM_DEVICECHANGE
            {
                string portName = Marshal.PtrToStringUni((IntPtr)(m.LParam.ToInt32() + Marshal.SizeOf(typeof(DEV_BROADCAST_PORT_Fixed))));
                switch (m.WParam.ToInt32())
                {
                case DBT_DEVICE_REMOVE_COMPLETE:        // USB拔出
                    DEV_BROADCAST_HDR dbhdr0 = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                    if (dbhdr0.dbch_devicetype == DBT_DEVTYP_PORT)
                    {
                        try
                        {
                            // comboPortName.Items.Remove(portName);

                            if (btnStart.Enabled)
                            {
                                getSerialPort(comboPLCPortName);
                                getSerialPort(comboSNPortName);
                            }
                            else
                            {
                                sp = new System.Media.SoundPlayer(global::SpotTestTester.Properties.Resources.ng);
                                sp.Play();
                                updateMessage(lstHistoryLog, "Port '" + portName + "' leaved.");
                                updateMessage(lstHistoryLog, "偵測到串口丟失,請重新設置后點擊開始,若無法啟動,點擊Restart再點擊Start。");
                                closePort(spPLC);
                                closePort(spSN);
                                pressStopButton();
                            }
                        }
                        catch (Exception ex)
                        {
                            sp = new System.Media.SoundPlayer(global::SpotTestTester.Properties.Resources.ng);
                            sp.Play();
                            updateMessage(lstHistoryLog, "Port '" + portName + "' leaved.");
                            updateMessage(lstHistoryLog, ex.Message);
                        }
                        Console.WriteLine("Port '" + portName + "' leaved.");
                    }

                    break;

                case DBT_DEVICEARRIVAL:                 // USB插入获取对应串口名称
                    DEV_BROADCAST_HDR dbhdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                    if (dbhdr.dbch_devicetype == DBT_DEVTYP_PORT)
                    {
                        getSerialPort(comboPLCPortName);
                        getSerialPort(comboSNPortName);
                        Console.WriteLine("Port '" + portName + "' arrived.");
                    }
                    break;
                }
            }
            base.WndProc(ref m);
        }
예제 #23
0
 protected override void DefWndProc(ref Message m)
 {
     if (m.Msg == 0x0219 && EnableToolStripMenuItem.Checked)
     {
         string disk = string.Empty;
         if (m.WParam.ToInt32() == 0x8000)
         {
             DEV_BROADCAST_HDR dbhdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
             if (dbhdr.dbch_devicetype == 0x00000002)
             {
                 DEV_BROADCAST_VOLUME dbv = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                 if (dbv.dbcv_flags == 0)
                 {
                     char[] volums = GetVolumes(dbv.dbcv_unitmask);
                     disk += volums[0].ToString() + ":";
                     ManagementObject diskinfo = new ManagementObject("win32_logicaldisk.deviceid=\"" + disk + "\"");
                     string           diskser  = diskinfo.Properties["VolumeSerialNumber"].Value.ToString();
                     msg(disk + " - " + diskser, "存储设备已插入");
                     if (blackid.Contains(diskser))
                     {
                         log("黑名单磁盘序列号号:" + diskser + " 取消复制!");
                         return;
                     }
                     if (blackdisk.Contains(disk.Substring(0, 1)))
                     {
                         log("黑名单分区号:" + disk + " 取消复制!");
                         return;
                     }
                     Thread th = new Thread(() =>
                     {
                         if (Properties.Settings.Default.sleep > 0)
                         {
                             log("延迟复制:将在 " + Properties.Settings.Default.sleep + "秒后进行复制");
                             Thread.Sleep(Properties.Settings.Default.sleep * 1000);
                             if (!Directory.Exists(disk + "\\"))
                             {
                                 log("在延迟复制期间存储设备已拔出,复制取消:" + disk + " - " + diskser, 1);
                                 return;
                             }
                         }
                         if (Properties.Settings.Default.autorm && Directory.Exists(dir + diskser))
                         {
                             log("清空输出目录:" + dir + diskser);
                             Directory.Delete(dir + diskser, true);
                         }
                         CopyDirectory(disk + "\\", dir + diskser);
                         log("设备数据复制完成:" + disk + " - " + diskser);
                     });
                     th.Start();
                 }
             }
         }
     }
     base.DefWndProc(ref m);
 }
예제 #24
0
        private static DeviceEventInfo TransformDeviceEvent(ref Message m)
        {
            var tm = new DeviceEventInfo {
                DEVICEEVENT = (ServicesAPI.SERVICE_CONTROL_DEVICEEVENT_Control)(int) m.WParam
            };

            DEV_BROADCAST_HDR dbh = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));

            tm.DeviceType = dbh.dbch_devicetype;

            switch (dbh.dbch_devicetype)
            {
            case dbch_devicetype.DBT_DEVTYP_DEVICEINTERFACE:
                DEV_BROADCAST_DEVICEINTERFACE dbdi = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_DEVICEINTERFACE));
                tm.DeviceId   = cstr_to_string(dbdi.dbcc_name);
                tm.DeviceName = ConvertDbccNameToFriendlyName(cstr_to_string(dbdi.dbcc_name));
                break;

            case dbch_devicetype.DBT_DEVTYP_HANDLE:
                DEV_BROADCAST_HANDLE dbbh = (DEV_BROADCAST_HANDLE)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HANDLE));
                tm.DeviceName = "Handle Id " + dbbh.dbch_handle.ToString();
                break;

            case dbch_devicetype.DBT_DEVTYP_OEM:
                DEV_BROADCAST_OEM dbo = (DEV_BROADCAST_OEM)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_OEM));
                tm.DeviceName = string.Format("OEM: {0} Value: {1}", dbo.dbco_identifier, dbo.dbco_suppfunc);
                break;

            case dbch_devicetype.DBT_DEVTYP_PORT:
                DEV_BROADCAST_PORT dbp            = (DEV_BROADCAST_PORT)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_PORT));
                IntPtr             pData          = (IntPtr)(m.LParam.ToInt32() + dbp.dbcp_size); // (*1)
                IntPtr             offsetDbcpName = Marshal.OffsetOf(typeof(DEV_BROADCAST_PORT), "dbcp_name");
                int len = (int)pData - (int)offsetDbcpName;
                tm.DeviceName = Marshal.PtrToStringAuto(offsetDbcpName, len);
                break;

            case dbch_devicetype.DBT_DEVTYP_VOLUME:
                DEV_BROADCAST_VOLUME dbv = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                tm.DeviceName = dbv.dbcv_unitmask.ToString();
                if (dbv.dbcv_flags != dbcv_flags.None)
                {
                    tm.DeviceName += " " + dbv.dbcv_flags.ToString();
                }
                break;
            }

            //dbh.dbch_devicetype == dbch_devicetype.
            //IntPtr pData = (IntPtr)(m.LParam.ToInt32() + Marshal.SizeOf(ps));  // (*1)


            return(tm);
        }
예제 #25
0
        /// <summary>
        /// 检测USB串口的拔插
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICE_CHANGE)                    // 捕获USB设备的拔出消息WM_DEVICECHANGE
            {
                switch (m.WParam.ToInt32())
                {
                case DBT_DEVICE_REMOVE_COMPLETE:                            // USB拔出
                    DEV_BROADCAST_HDR dbhdr0 = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                    if (dbhdr0.dbch_devicetype == DBT_DEVTYP_PORT)
                    {
                        string portName = Marshal.PtrToStringUni((IntPtr)(m.LParam.ToInt32() + Marshal.SizeOf(typeof(DEV_BROADCAST_PORT_Fixed))));
                        LogHelper.LibraryLogger.Instance.WriteLog(LogHelper.LibraryLogger.libLogLevel.Error, "串口掉线,串口号:" + portName);
                    }
                    break;

                case DBT_DEVICEARRIVAL:                                     // USB插入获取对应串口名称
                    DEV_BROADCAST_HDR dbhdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                    if (dbhdr.dbch_devicetype == DBT_DEVTYP_PORT)
                    {
                        string portName = Marshal.PtrToStringUni((IntPtr)(m.LParam.ToInt32() + Marshal.SizeOf(typeof(DEV_BROADCAST_PORT_Fixed))));
                        LogHelper.LibraryLogger.Instance.WriteLog(LogHelper.LibraryLogger.libLogLevel.Error, "串口接入,串口号:" + portName);
                    }
                    break;
                }
            }
            if (m.Msg == WM_SYSCOMMAND && ((int)m.WParam == SC_CLOSE))
            {
                // 点击winform右上关闭按钮 f
                // 加入想要的逻辑处理
                ExitForm     exit = new ExitForm();
                DialogResult dr   = exit.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    isStop = true;
                    closeCom();
                    timer1.Stop();
                    Application.Exit();
                }
                else if (dr == DialogResult.Yes)
                {
                    // 改关闭效果为最小化
                    this.WindowState = FormWindowState.Minimized;
                    this.Hide();
                    return;
                }
                else if (dr == DialogResult.Cancel)
                {
                    return;
                }
            }
            base.WndProc(ref m);
        }
예제 #26
0
        private void TestStructure(IntPtr lParam)
        {
            DEV_BROADCAST_HDR hdr = Marshal.PtrToStructure <DEV_BROADCAST_HDR>(lParam);

            if (hdr.deviceType == DeviceType.DeviceInterface)
            {
                Console.WriteLine("DBT_DEVTYP_DEVICEINTERFACE");
                DEV_BROADCAST_DEVICEINTERFACE device = Marshal.PtrToStructure <DEV_BROADCAST_DEVICEINTERFACE>(lParam);
                IntPtr offsetPtr = new IntPtr(lParam.ToInt32() + sizeof(int) * 3 + Marshal.SizeOf <Guid>());
                string name      = Marshal.PtrToStringAuto(offsetPtr);
                Console.WriteLine(name);
            }
        }
예제 #27
0
        //----------------
        private void DoBroadcastHdr(Message m)
        {
            //IntPtr pXXX;
            String            text = String.Empty;
            DEV_BROADCAST_HDR hdr  = (DEV_BROADCAST_HDR)m.GetLParam(typeof(DEV_BROADCAST_HDR));

            if (hdr.dbch_devicetype == DbtDevTyp.Port)
            {
                DoDevTypPort(ref m, ref text, ref hdr);
            }
            else if (hdr.dbch_devicetype == DbtDevTyp.Handle)
            {
                DoDevTypHandle(ref m, ref text);
            }
        }
예제 #28
0
        private void DoBroadcastHdr(WndProcClient.WindowMessage m)
        {
            //IntPtr pXXX;
            String            text = String.Empty;
            DEV_BROADCAST_HDR hdr  = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.lParam, typeof(DEV_BROADCAST_HDR));

            if (hdr.dbch_devicetype == DbtDevTyp.Port)
            {
                DoDevTypPort(ref m, ref text, ref hdr);
            }
            else if (hdr.dbch_devicetype == DbtDevTyp.Handle)
            {
                DoDevTypHandle(ref m, ref text);
            }
        }
        ///  <summary>
        ///  比较设备的路径名,用于发现最近连接的或者移除的正在通讯的匹配设备名称
        ///  Compares two device path names. Used to find out if the device name
        ///  of a recently attached or removed device matches the name of a
        ///  device the application is communicating with.
        ///  </summary>
        ///  <param name="m"> 一个 WM_DEVICECHANGE 消息. 调用 RegisterDeviceNotification 函数
        ///  以便 WM_DEVICECHANGE 消息可以传递到 OnDeviceChange 例行程序.. </param>
        ///  <param name="mydevicePathName"> a device pathname returned by
        ///  SetupDiGetDeviceInterfaceDetail in an SP_DEVICE_INTERFACE_DETAIL_DATA structure. </param>
        ///  <returns>
        ///  名称匹配返回True,否则返回False
        ///  </returns>
        public Boolean DeviceNameMatch(Message m, String mydevicePathName)
        {
            Int32 stringSize;

            try
            {
                DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
                DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();

                // Message 的 LParam 参数  is 指向 DEV_BROADCAST_HDR 结构的指针.
                Marshal.PtrToStructure(m.LParam, devBroadcastHeader);

                if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
                {
                    // dbch_devicetype 参数指出了应用设备的接口
                    // 因此 LParam 参数实际是以DEV_BROADCAST_HDR开始的 DEV_BROADCAST_INTERFACE结构

                    // 通过减去结构中不是dbch_name部分的32字节后得到了字符的个数,由于一个字符两个字节,所以再除以2
                    stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);

                    //  devBroadcastDeviceInterface中的dbcc_name 参数包含了设备名称
                    // 去掉前后的空格以匹配字符串长度
                    devBroadcastDeviceInterface.dbcc_name = new Char[stringSize + 1];

                    // 将数据从不受管理的数据块传输到受管理的devBroadcastDeviceInterface对象中
                    Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface);

                    // 将设备名用String类型存储
                    String DeviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);

                    // 比较新连接的设备名字和我们已知的设备(mydevicePathName)名字,匹配返回true
                    if ((String.Compare(DeviceNameString, mydevicePathName, true) == 0))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(false);
        }
예제 #30
0
        // Get device name from notification message.
        // Also checks checkGuid with the GUID from the message to check the notification
        // is for a relevant device. Other messages might be received.
		public static string GetNotifyMessageDeviceName(Message m, Guid checkGuid)
		{
			int stringSize;

		
			DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
			DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();

			// The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure.

			Marshal.PtrToStructure(m.LParam, devBroadcastHeader);

			if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
			{
				// The dbch_devicetype parameter indicates that the event applies to a device interface.
				// So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure, 
				// which begins with a DEV_BROADCAST_HDR.

				// Obtain the number of characters in dbch_name by subtracting the 32 bytes
				// in the strucutre that are not part of dbch_name and dividing by 2 because there are 
				// 2 bytes per character.

                stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);

				// The dbcc_name parameter of devBroadcastDeviceInterface contains the device name. 
				// Trim dbcc_name to match the size of the String.         

				devBroadcastDeviceInterface.dbcc_name = new char[stringSize + 1];

				// Marshal data from the unmanaged block pointed to by m.LParam 
				// to the managed object devBroadcastDeviceInterface.

				Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface);

                // Check if message is for the GUID
                if (devBroadcastDeviceInterface.dbcc_classguid != checkGuid)
                    return null;

                // Store the device name in a String.
                string deviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);

                return deviceNameString;
	
			}
            return null;
		}
예제 #31
0
        private string GetDevicePathFromBroadcast(IntPtr deviceInfo)
        {
            DEV_BROADCAST_HDR header = new DEV_BROADCAST_HDR();

            Marshal.PtrToStructure(deviceInfo, header);

            if (header.dbchDevicetype != DBT_DEVTYP_DEVICEINTERFACE)
            {
                return(null);
            }

            DEV_BROADCAST_DEVICEINTERFACE_2 devInterface = new DEV_BROADCAST_DEVICEINTERFACE_2();
            UInt32 stringLength = (header.dbchSize - 32) / 2;

            devInterface.dbccName = new char[stringLength + 1];
            Marshal.PtrToStructure(deviceInfo, devInterface);
            return(new String(devInterface.dbccName, 0, (int)stringLength));
        }
예제 #32
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="LParam"></param>
            /// <returns></returns>
            public static bool NameAndClass(IntPtr LParam, ref String name)
            {
                DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
                DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();

                Marshal.PtrToStructure(LParam, devBroadcastHeader);
                if ((devBroadcastHeader.dbch_devicetype == DbtDevtypDeviceinterface))
                {
                    Int32 stringSize = Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);

                    Array.Resize(ref devBroadcastDeviceInterface.dbcc_name, stringSize);
                    Marshal.PtrToStructure(LParam, devBroadcastDeviceInterface);
                    name = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);
                    name = FriendlyName(name);
                    return(true);
                }
                return(false);
            }
예제 #33
0
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            DeviceEvent lEvent;

            lEvent = (DeviceEvent)m.WParam.ToInt64();
            switch (lEvent)
            {
            case DeviceEvent.DBT_DEVICEARRIVAL:    //[Insert]
                DEV_BROADCAST_HDR dbhdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                if (dbhdr.dbch_devicetype == DBT_DEVTYP_PORT)
                {
                    string portName = Marshal.PtrToStringUni((IntPtr)(m.LParam.ToInt64() + Marshal.SizeOf(typeof(DEV_BROADCAST_PORT_Fixed))));
                    Console.WriteLine("Port '" + portName + "' arrived.");
                }
                break;

            case DeviceEvent.DBT_DEVICEREMOVECOMPLETE:    //[REmove]
                DEV_BROADCAST_HDR dbhdr2 = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                if (dbhdr2.dbch_devicetype == DBT_DEVTYP_PORT)
                {
                    string portName2 = Marshal.PtrToStringUni((IntPtr)(m.LParam.ToInt64() + Marshal.SizeOf(typeof(DEV_BROADCAST_PORT_Fixed))));
                    Console.WriteLine("Port '" + portName2 + "' arrived.");
                    if (!portName.Equals(portName2))
                    {
                        break;
                    }
                    commRemoveCallBack();
                    getCommPorts();
                    StringBuilder strBu = new StringBuilder();
                    strBu.Append(StringUtils.findCom);
                    strBu.Append(portName2);
                    strBu.Append(StringUtils.Com_Remove);
                    MessageBox.Show(strBu.ToString());
                }
                break;

            case DeviceEvent.DBT_DEVNODES_CHANGED:    //[Device List Have Changed]
                break;

            default:
                break;
            }
        }
예제 #34
0
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == Win32Constants.WM_DEVICECHANGE && wParam.ToInt32().TryConvertToEnum <DeviceEvent>(out var nEventType) && (nEventType == DeviceEvent.DEVICEARRIVAL || nEventType == DeviceEvent.DEVICEREMOVECOMPLETE))
            {
                DEV_BROADCAST_HDR hdr = new DEV_BROADCAST_HDR();
                Marshal.PtrToStructure(lParam, hdr);

                if (hdr.dbch_devicetype == Win32Constants.DBT_DEVTYP_VOLUME)
                {
                    DEV_BROADCAST_VOLUME volume = new DEV_BROADCAST_VOLUME();
                    Marshal.PtrToStructure(lParam, volume);

                    if (nEventType == DeviceEvent.DEVICEREMOVECOMPLETE)
                    {
                        try
                        {
                            var driveLetter = UsbDevice.DriveMaskToLetter(volume.dbcv_unitmask);
                            UsbDeviceRemovedEvent?.Invoke(this, new UsbDeviceRemovedEventArgs(driveLetter));
                        }
                        catch (Exception e)
                        {
                            UsbDeviceErrorEvent?.Invoke(this, new UsbDeviceExceptionEventArgs(e));
                        }
                    }
                    else if (nEventType == DeviceEvent.DEVICEARRIVAL)
                    {
                        try
                        {
                            var driveLetter   = UsbDevice.DriveMaskToLetter(volume.dbcv_unitmask);
                            var usbDeviceInfo = UsbDevice.GetUSBDeviceInfo(driveLetter);

                            UsbDeviceArrivedEvent?.Invoke(this, new UsbDeviceArrivedEventArgs(driveLetter, usbDeviceInfo));
                        }
                        catch (Exception e)
                        {
                            UsbDeviceErrorEvent?.Invoke(this, new UsbDeviceExceptionEventArgs(e));
                        }
                    }
                }
            }

            return(IntPtr.Zero);
        }
예제 #35
0
        internal void OnDeviceChange(Message m)
        {
            DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
            DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();

            if ((int)m.LParam != 0)
            {
                Marshal.PtrToStructure(m.LParam, devBroadcastHeader);
            }
            else
            {
                return;
            }

            if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
            {
                Int32 stringSize = Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);
                Array.Resize(ref devBroadcastDeviceInterface.dbcc_name, stringSize);
                Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface);
                String deviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);

                USB_Printing = true;

                if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL))
                {
                    textBox1.AppendText(deviceNameString);
                    textBox1.AppendText(" attached\r\n");
                }
                else if ((m.WParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE))
                {
                    textBox1.AppendText(deviceNameString);
                    textBox1.AppendText(" removed\r\n");
                }

                USB_Printing = false;

            }
        }
        // Static routine to parse out the device type from the IntPtr received in WndProc
        public bool CheckEventDetails(IntPtr pReason, IntPtr pHdr)
        {
            var iValue = pReason.ToInt32();

            // Check the event type
            if (iValue != DBT_DEVICEREMOVECOMPLETE && iValue != DBT_DEVICEARRIVAL)
                return false;

            // Do we have device details yet?
            if (pHdr == IntPtr.Zero)
                return false;

            // Parse the first chunk
            var pbh = new DEV_BROADCAST_HDR();
            Marshal.PtrToStructure(pHdr, pbh);

            // Check the device type
            if (pbh.dbch_devicetype != DBT_DEVTYP_DEVICEINTERFACE)
                return false;

            // Only parse this if the right device type
            var pdi = new DEV_BROADCAST_DEVICEINTERFACE();
            Marshal.PtrToStructure(pHdr, pdi);

            return (pdi.dbcc_classguid == category);
        }
예제 #37
0
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_CREATE:
                    try
                    {
                        DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE();
                        IntPtr devBroadcastDeviceInterfaceBuffer;
                        IntPtr deviceNotificationHandle = IntPtr.Zero;
                        Int32 size = 0;

                        // frmMy is the form that will receive device-change messages.


                        size = Marshal.SizeOf(devBroadcastDeviceInterface);
                        devBroadcastDeviceInterface.dbcc_size = size;
                        devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
                        devBroadcastDeviceInterface.dbcc_reserved = 0;
                        devBroadcastDeviceInterface.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE.ToByteArray();
                        devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size);
                        Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true);


                        deviceNotificationHandle = NativeMethods.RegisterDeviceNotification(this.Handle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE);
                    }
                    catch { }

                    break;

                case WM_DEVICECHANGE:
                    // The WParam value identifies what is occurring.
                    WM_DEVICECHANGE_enum n = (WM_DEVICECHANGE_enum)m.WParam;
                    int l = (int)m.LParam;
                    if (n == WM_DEVICECHANGE_enum.DBT_DEVICEREMOVEPENDING)
                    {
                        Console.WriteLine("DBT_DEVICEREMOVEPENDING");
                    }
                    if (n == WM_DEVICECHANGE_enum.DBT_DEVNODES_CHANGED)
                    {
                        Console.WriteLine("DBT_DEVNODES_CHANGED");
                    }
                    if (n == WM_DEVICECHANGE_enum.DBT_DEVICEARRIVAL || n == WM_DEVICECHANGE_enum.DBT_DEVICEREMOVECOMPLETE)
                    {
                        Console.WriteLine(((WM_DEVICECHANGE_enum)n).ToString());

                        DEV_BROADCAST_HDR hdr = new DEV_BROADCAST_HDR();
                        Marshal.PtrToStructure(m.LParam, hdr);

                        try
                        {

                            switch (hdr.dbch_devicetype)
                            {
                                case DBT_DEVTYP_DEVICEINTERFACE:
                                    DEV_BROADCAST_DEVICEINTERFACE inter = new DEV_BROADCAST_DEVICEINTERFACE();
                                    Marshal.PtrToStructure(m.LParam, inter);
                                    log.InfoFormat("Interface {0}", ASCIIEncoding.Unicode.GetString(inter.dbcc_name, 0, inter.dbcc_size - (4 * 3)));
                                    break;
                                case DBT_DEVTYP_PORT:
                                    DEV_BROADCAST_PORT prt = new DEV_BROADCAST_PORT();
                                    Marshal.PtrToStructure(m.LParam, prt);
                                    log.InfoFormat("port {0}", ASCIIEncoding.Unicode.GetString(prt.dbcp_name, 0, prt.dbcp_size - (4 * 3)));
                                    break;
                            }

                        }
                        catch { }

                        //string port = Marshal.PtrToStringAuto((IntPtr)((long)m.LParam + 12));
                        //Console.WriteLine("Added port {0}",port);
                    }
                    log.InfoFormat("Device Change {0} {1} {2}", m.Msg, (WM_DEVICECHANGE_enum)m.WParam, m.LParam);

                    if (DeviceChanged != null)
                    {
                        try
                        {
                            DeviceChanged((WM_DEVICECHANGE_enum)m.WParam);


                        }
                        catch { }
                    }

                    foreach (Plugin.Plugin item in MissionPlanner.Plugin.PluginLoader.Plugins)
                    {
                        item.Host.ProcessDeviceChanged((WM_DEVICECHANGE_enum)m.WParam);
                    }

                    break;
                default:

                    break;
            }
            base.WndProc(ref m);
        }
예제 #38
0
        private void OnDeviceInterfaceChanged(DeviceEvent eventType, Message message, DEV_BROADCAST_HDR broadcastHeader)
        {
            int stringSize = Convert.ToInt32((broadcastHeader.dbch_size - 32) / 2);

            var deviceInterface = new DEV_BROADCAST_DEVICEINTERFACE();
            Array.Resize(ref deviceInterface.dbcc_name, stringSize);
            Marshal.PtrToStructure(message.LParam, deviceInterface);
            var classId = new Guid(deviceInterface.dbcc_classguid);
            var deviceName = new string(deviceInterface.dbcc_name, 0, stringSize);
            Debug.Print("Hardware.OnDeviceInterfaceChanged(): {0} {2} {1}", eventType, deviceName, classId);

            var eh = DeviceInterfaceChanged;
            if (eh != null) {
                eh(this, new DeviceInterfaceChangedArgs(eventType, classId, deviceName));
            }
        }
예제 #39
0
 private void OnDashboardLoad(object sender, EventArgs e)
 {
     if (string.IsNullOrEmpty(Adb.Exe))
     {
         MessageBox.Show(Resources.ADB_NOT_FOUND_MESSAGE, Resources.ADB_NOT_FOUND_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         Close();
     }
     else
     {
         DEV_BROADCAST_HDR dbi = new DEV_BROADCAST_HDR
         {
             ClassGuid = CLASS_GUID,
             DeviceType = DBT_DEVTYP_PORT,
             Reserved = 0,
             Name = 0
         };
         dbi.Size = Marshal.SizeOf(dbi);
         IntPtr buffer = Marshal.AllocHGlobal(dbi.Size);
         Marshal.StructureToPtr(dbi, buffer, true);
         hNotification = RegisterDeviceNotification(Handle, buffer, 0);
         Console.SetOut(new Writer(OutputText));
         OutputText.TextChanged += (a, b) =>
         {
             OutputText.SelectionStart = OutputText.Text.Length;
             OutputText.ScrollToCaret();
         };
         Profile.Click += (a, b) => { Process.Start("http://forum.xda-developers.com/member.php?u=5490832"); };
         Profile.MouseEnter += (a, b) =>
         {
             Profile.Cursor = Cursors.Hand;
             Profile.ForeColor = Color.MidnightBlue;
         };
         Profile.MouseLeave += (a, b) =>
         {
             Profile.Cursor = Cursors.Default;
             Profile.ForeColor = Color.RoyalBlue;
         };
         RebootBox.Items.Add(new RebootItem
         {
             Text = Resources.REBOOT_BOOTLOADER,
             Value = "bootloader"
         });
         RebootBox.Items.Add(new RebootItem
         {
             Text = Resources.REBOOT_DOWNLOAD,
             Value = "download"
         });
         RebootBox.Items.Add(new RebootItem
         {
             Text = Resources.REBOOT_RECOVERY,
             Value = "recovery"
         });
         RebootBox.Items.Add(new RebootItem
         {
             Text = Resources.REBOOT_SYSTEM,
             Value = "system"
         });
         RebootBox.SelectedIndex = RebootBox.Items.Count - 1;
         Rooted.Text = string.Format(Resources.ROOT_STATUS, "Unknown");
         Website.Click += (a, b) => { Process.Start("http://www.vaibhavpandey.com"); };
         Website.MouseEnter += (a, b) =>
         {
             Website.Cursor = Cursors.Hand;
             Website.ForeColor = Color.MidnightBlue;
         };
         Website.MouseLeave += (a, b) =>
         {
             Website.Cursor = Cursors.Default;
             Website.ForeColor = Color.RoyalBlue;
         };
         SendMessage(DevicesBox.Handle, COMBOBOX_SETIH, -1, 24);
         SendMessage(RebootBox.Handle, COMBOBOX_SETIH, -1, 24);
         ResizeTextBox(ConnectBox, 22);
         Console.WriteLine(Resources.OUTPUT_CHECKING_VERSION);
         RunInBackground((a, b) =>
         {
             Worker.ReportProgress(1);
             b.Result = Adb.Version();
             Worker.ReportProgress(100);
         },
         (a, b) =>
         {
             Version v;
             if ((v = (Version)b.Result) != null)
             {
                 Console.WriteLine(Resources.OUTPUT_VERSION_FOUND, v);
                 Version.Text = v.ToString();
                 Refresh.PerformClick();
             }
             else
             {
                 Console.WriteLine(Resources.OUTPUT_VERSION_NOT_FOUND, v);
             }
         });
     }
 }
예제 #40
0
    /// <summary>
    /// Handles the window message when a drive change is in progress or finished
    /// </summary>
    /// <param name="msg">Window message</param>
    /// <returns>true, if the message was handled</returns>
    public static bool HandleDeviceChangedMessage(Message msg)
    {
      DEV_BROADCAST_HDR hdr = new DEV_BROADCAST_HDR();
      DEV_BROADCAST_VOLUME vol = new DEV_BROADCAST_VOLUME();

      try
      {
        var deviceInterface = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(msg.LParam, typeof(DEV_BROADCAST_DEVICEINTERFACE));

        // get friendly device name
        string deviceName = String.Empty;
        string[] values = deviceInterface.dbcc_name.Split('#');
        if (values.Length >= 3)
        {
          string deviceType = values[0].Substring(values[0].IndexOf(@"?\", StringComparison.Ordinal) + 2);
          string deviceInstanceID = values[1];
          string deviceUniqueID = values[2];
          string regPath = @"SYSTEM\CurrentControlSet\Enum\" + deviceType + "\\" + deviceInstanceID + "\\" + deviceUniqueID;
          Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regPath);
          if (regKey != null)
          {
            // use the friendly name if it exists
            object result = regKey.GetValue("FriendlyName");
            if (result != null)
            {
              deviceName = result.ToString();
            }
            // if not use the device description's last part
            else
            {
              result = regKey.GetValue("DeviceDesc");
              if (result != null)
              {
                deviceName = result.ToString().Contains(@"%;") ? result.ToString().Substring(result.ToString().IndexOf(@"%;", StringComparison.Ordinal) + 2) : result.ToString();
              }
            }
          }
        }
        if (!string.IsNullOrEmpty(deviceName) && deviceName.Contains("Microsoft Virtual DVD-ROM"))
        {
          Log.Debug("Ignoring Microsoft Virtual DVD-ROM device change event");

          return true;
        }
      }
      catch
      { }

      try
      {
        if (msg.WParam.ToInt32() == DBT_DEVICEARRIVAL)
        {
          // new device
          hdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(msg.LParam, hdr.GetType());
          if (hdr.devicetype == DBT_DEVTYPE_VOLUME)
          {
            vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(msg.LParam, vol.GetType());
            return DeviceNew(vol);
          }
        }
        else if (msg.WParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE)
        {
          // device remove
          hdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(msg.LParam, hdr.GetType());
          if (hdr.devicetype == DBT_DEVTYPE_VOLUME)
          {
            vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(msg.LParam, vol.GetType());
            return DeviceRemoved(vol);
          }
        }
      }
      catch (Exception ex)
      {
        Log.Error("Error in handling device changed message: {0}", ex);
      }
      return false;
    }
예제 #41
0
 public static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, ref DEV_BROADCAST_HDR filter, int Flags);
예제 #42
0
        private void OnDeviceChange(Message message)
        {
            var eventType = (DeviceEvent)message.WParam.ToInt32();
            if (message.LParam != IntPtr.Zero) {
                var broadcastHeader = new DEV_BROADCAST_HDR();
                Marshal.PtrToStructure(message.LParam, broadcastHeader);

                var deviceType = (DeviceType)broadcastHeader.dbch_devicetype;
                switch (deviceType) {
                    case DeviceType.DeviceInterface:
                        OnDeviceInterfaceChanged(eventType, message, broadcastHeader);
                        break;

                    case DeviceType.Volume:
                        OnVolumeChanged(eventType, message);
                        break;

                    default:
                        switch (eventType) {
                            case DeviceEvent.DeviceArrival:
                                Debug.Print("Hardware.OnDeviceChange(): Device arrived: {0}", deviceType);
                                break;
                            case DeviceEvent.DeviceRemoveComplete:
                                Debug.Print("Hardware.OnDeviceChange(): Device removed: {0}", deviceType);
                                break;
                            default:
                                Debug.Print("Hardware.OnDeviceChange(): {0}", eventType);
                                break;
                        }
                        break;
                }
            }
        }
예제 #43
0
 public static extern IntPtr RegisterDeviceNotification(HWND hRecipient, DEV_BROADCAST_HDR NotificationFilter, uint Flags);
예제 #44
0
        public static void Initialize(Window window)
        {
            DEV_BROADCAST_HDR _data = new DEV_BROADCAST_HDR();
            _data.dbch_size = Marshal.SizeOf(_data);
            _data.dbch_devicetype = DBCH_DEVICETYPE.DBT_DEVTYP_DEVICEINTERFACE;

            IntPtr _buffer = Marshal.AllocHGlobal(_data.dbch_size);
            Marshal.StructureToPtr(_data, _buffer, true);

            IntPtr _hwnd = new WindowInteropHelper(window).Handle;

            NativeMethods.RegisterDeviceNotification(
                _hwnd,
                _buffer,
                FLAGS.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES
                );

            HwndSource.FromHwnd(_hwnd).AddHook(DeviceHook);
        }