/// <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);
        }
Example #2
0
            protected override void WndProc(ref Message message)
            {
                base.WndProc(ref message);
                if (message.Msg == NativeMethods.WM_SHOWME)
                {
                    TheParent.ShowMe();
                }
                if ((message.Msg == WM_DEVICECHANGE) && (message.LParam != IntPtr.Zero))
                {
                    DEV_BROADCAST_VOLUME volume = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(message.LParam, typeof(DEV_BROADCAST_VOLUME));

                    if (volume.dbcv_devicetype == DBT_DEVTYP_VOLUME)// || lpdb.dbch_devicetype == DBT_DEVTYP_VOLUME)
                    {
                        switch (message.WParam.ToInt32())
                        {
                        case DBT_DEVICEARRIVAL:
                            SignalDeviceChange(UsbStateChange.Added, volume);
                            break;

                        case DBT_DEVICEQUERYREMOVE:
                            //SignalDeviceChange(UsbStateChange.Removing, volume);
                            break;

                        case DBT_DEVICEREMOVECOMPLETE:
                            SignalDeviceChange(UsbStateChange.Removed, volume);
                            break;
                        }
                    }
                }
            }
Example #3
0
        //Mad props to https://gist.github.com/bitlimakina/9421370

        protected override void WndProc(ref Message message)
        {
            base.WndProc(ref message);

            if ((message.Msg != WM_DEVICECHANGE) || (message.LParam == IntPtr.Zero))
            {
                return;
            }

            DEV_BROADCAST_VOLUME volume = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(message.LParam, typeof(DEV_BROADCAST_VOLUME));

            if (volume.dbcv_devicetype == DBT_DEVTYP_VOLUME)
            {
                switch (message.WParam.ToInt32())
                {
                // New device inserted...
                case DBT_DEVICEARRIVAL:
                    DetectMountedVolumes();
                    break;

                // Device Removed.
                case DBT_DEVICEREMOVECOMPLETE:
                    DetectMountedVolumes();         //Refresh the list of active devices in MicroFormat
                    break;
                }
            }
        }
Example #4
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);
        }
        /// <summary>
        /// Extracts the Volume letter and sends a gui message with the extracted volume letter so that other plugins can add this drive out of there virtual directory
        /// </summary>
        /// <param name="volumeInformation">Volume Informations</param>
        /// <returns>true, if the message was handled; false otherwise</returns>
        private static bool DeviceNew(DEV_BROADCAST_VOLUME volumeInformation)
        {
            char   volumeLetter = GetVolumeLetter(volumeInformation.UnitMask);
            string path         = (volumeLetter + @":").ToUpperInvariant();
            string driveName    = Utils.GetDriveName(path);

            if (Utils.IsRemovable(path) || Utils.IsHD(path))
            {
                Log.Debug("Detected new device: {0}", volumeLetter);
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ADD_REMOVABLE_DRIVE, 0, 0, 0, 0, 0, 0);
                msg.Label  = path;
                msg.Label2 = String.Format("({0}) {1}", path, driveName);
                GUIGraphicsContext.SendMessage(msg);
                return(true);
            }
            else if (Utils.IsDVD(path))
            {
                Log.Debug("Detected new optical media: {0}", volumeLetter);
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VOLUME_INSERTED, 0, 0, 0, 0, 0, 0);
                msg.Label = path;
                GUIGraphicsContext.SendMessage(msg);
                return(true);
            }
            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);
        }
Example #7
0
        public static void WndProc(int msg, IntPtr wparam, IntPtr lparam)
        {
            if (msg == WM_DEVICECHANGE && lparam != IntPtr.Zero)
            {
                DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(lparam, typeof(DEV_BROADCAST_VOLUME));

                if (vol.dbcv_devicetype == DBT_DEVTYPVOLUME)
                {
                    char driveLetter = DriveMaskToLetter(vol.dbcv_unitmask);

                    switch (wparam.ToInt32())
                    {
                    case DBT_DEVICEARRIVAL:
                        Messenger.Default.Send(new RemovableDriveMessage
                        {
                            Added       = true,
                            DriveLetter = driveLetter
                        });
                        break;

                    case DBT_DEVICEREMOVALCOMPLETE:
                        Messenger.Default.Send(new RemovableDriveMessage
                        {
                            Added       = false,
                            DriveLetter = driveLetter
                        });
                        break;
                    }
                }
            }
        }
Example #8
0
 protected override void WndProc(ref Message m)
 {
     try
     {
         if (m.Msg == WM_DEVICECHANGE)
         {
             DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
             if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
             {
                 if (Helpers.Settings.config.sdDriveLetter.Contains(DriveMaskToLetter(vol.dbcv_unitmask).ToString()))
                 {
                     locationToolStripComboBox.SelectedIndex = 1;
                     XciHelper.LoadXcisInBackground();
                     UpdateSdInfo();
                 }
             }
             if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
             {
                 if (Helpers.Settings.config.sdDriveLetter.Contains(DriveMaskToLetter(vol.dbcv_unitmask).ToString()))
                 {
                     locationToolStripComboBox.SelectedIndex = 0;
                     XciHelper.LoadXcisInBackground();
                     UpdateSdInfo();
                 }
             }
         }
         base.WndProc(ref m);
     }
     catch { }
 }
Example #9
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);
        }
Example #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);
        }
Example #11
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);
        }
    /// <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;
    }
Example #13
0
            protected override void WndProc(ref Message message)
            {
                base.WndProc(ref message);

                if ((message.Msg == WM_DEVICECHANGE) && (message.LParam != IntPtr.Zero))
                {
                    DEV_BROADCAST_VOLUME volume = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(
                        message.LParam, typeof(DEV_BROADCAST_VOLUME));

                    if (volume.dbcv_devicetype == DBT_DEVTYP_VOLUME)
                    {
                        switch (message.WParam.ToInt32())
                        {
                        case DBT_DEVICEARRIVAL:
                            SignalDeviceChange(UsbStateChange.Added, volume);
                            break;

                        case DBT_DEVICEQUERYREMOVE:
                            // can intercept
                            break;

                        case DBT_DEVICEREMOVECOMPLETE:
                            SignalDeviceChange(UsbStateChange.Removed, volume);
                            break;
                        }
                    }
                }
            }
Example #14
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);
        }
        private static DEV_BROADCAST_VOLUME BroadcastVolumeFromPointer(IntPtr broadcastVolumePtr)
        {
            DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)(
                Marshal.PtrToStructure(broadcastVolumePtr, typeof(DEV_BROADCAST_VOLUME)) ??
                new DEV_BROADCAST_VOLUME());

            return(vol);
        }
        /// <summary>
        /// Extracts the Volume letter and sends a gui message with the extracted volume letter so that other plugins can remove this drive out of there virtual directory
        /// </summary>
        /// <param name="volumeInformation">Volume Informations</param>
        /// <returns>true, if the message was handled; false otherwise</returns>
        private static bool DeviceRemoved(DEV_BROADCAST_VOLUME volumeInformation)
        {
            char   volumeLetter = GetVolumeLetter(volumeInformation.UnitMask);
            string path         = (volumeLetter + @":").ToUpperInvariant();

            if (DaemonTools.GetLastVirtualDrive() == path)
            {
                Log.Debug("Ignoring Microsoft Virtual DVD-ROM device change event. Drive letter: {0}", path);
                return(true);
            }

            _volumeRemovalTime = DateTime.Now;
            TimeSpan tsMount;

            if (_mountTime == _mountDetectedTime) // Time not init
            {
                tsMount = DateTime.Now - _volumeInsertTime;
            }
            else
            {
                tsMount = DateTime.Now - _mountTime;
            }
            TimeSpan tsExamineCD    = DateTime.Now - _examineCDTime;
            TimeSpan tsVolumeInsert = DateTime.Now - _volumeInsertTime;

            if (!Utils.IsDVD(path))
            {
                Log.Debug("Detected device remove: {0}", volumeLetter);
                var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_REMOVE_REMOVABLE_DRIVE, 0, 0, 0, 0, 0, 0)
                {
                    Label  = path,
                    Label2 = String.Format("({0})", path)
                };
                GUIGraphicsContext.SendMessage(msg);
                return(true);
            }
            if (Utils.IsDVD(path))
            {
                // AnyDVD is causing media removed & inserted events when Mount/Unmount Volume
                // We need to filter out those as it could trigger false autoplay event
                if (tsExamineCD.TotalMilliseconds < _volumeRemovalDelay || tsMount.TotalMilliseconds < _volumeRemovalDelay || tsVolumeInsert.TotalMilliseconds < _volumeRemovalDelay)
                {
                    Log.Debug("Ignoring volume removed event - drive {0} - time after Mount {1} s", volumeLetter, tsMount.TotalMilliseconds / 1000);
                    return(false);
                }
                Log.Debug("Detected optical media removal: {0}", volumeLetter);
                Log.Debug("  time after ExamineCD {0} s", tsExamineCD.TotalMilliseconds / 1000);
                var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VOLUME_REMOVED, 0, 0, 0, 0, 0, 0)
                {
                    Label = path
                };
                GUIGraphicsContext.SendMessage(msg);
                return(true);
            }
            return(false);
        }
Example #17
0
        // segnala il cambio bi stato del dispositivo
        void SignalDeviceChange(UsbStateChange state, DEV_BROADCAST_VOLUME volume)
        {
            string name = ToUnitName(volume.dbcv_unitmask);

            if (StateChanged != null)
            {
                UsbDisk disk = new UsbDisk(name);
                StateChanged(new UsbStateChangedEventArgs(state, disk));
            }
        }
Example #18
0
            private void SignalDeviceChange(UsbStateChange state, DEV_BROADCAST_VOLUME volume)
            {
                string name = ToUnitName(volume.dbcv_unitmask);

                if (StateChanged != null)
                {
                    UsbDisk disk = new UsbDisk(name);
                    StateChanged(new UsbStateChangedEventArgs(state, disk));
                }
            }
        /// <summary>
        /// Extracts the Volume letter and sends a gui message with the extracted volume letter so that other plugins can add this drive out of there virtual directory
        /// </summary>
        /// <param name="volumeInformation">Volume Informations</param>
        /// <returns>true, if the message was handled; false otherwise</returns>
        private static bool DeviceNew(DEV_BROADCAST_VOLUME volumeInformation)
        {
            char   volumeLetter = GetVolumeLetter(volumeInformation.UnitMask);
            string path         = (volumeLetter + @":").ToUpperInvariant();
            string driveName    = Utils.GetDriveName(path);

            _volumeInsertTime = DateTime.Now;
            TimeSpan tsMount;

            if (_mountTime == _mountDetectedTime) // Time not init
            {
                tsMount = DateTime.Now - _volumeInsertTime;
            }
            else
            {
                tsMount = DateTime.Now - _mountTime;
            }

            TimeSpan tsExamineCD     = DateTime.Now - _examineCDTime;
            TimeSpan tsVolumeRemoval = DateTime.Now - _volumeRemovalTime;

            if (Utils.IsRemovable(path) || Utils.IsHD(path))
            {
                Log.Debug("Detected new device: {0}", volumeLetter);
                var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ADD_REMOVABLE_DRIVE, 0, 0, 0, 0, 0, 0)
                {
                    Label  = path,
                    Label2 = String.Format("({0}) {1}", path, driveName)
                };
                GUIGraphicsContext.SendMessage(msg);
                return(true);
            }
            if (Utils.IsDVD(path))
            {
                // AnyDVD is causing media removed & inserted events when waking up from S3/S4
                // We need to filter out those as it could trigger false autoplay event
                if (tsExamineCD.TotalMilliseconds < _volumeRemovalDelay ||
                    (tsVolumeRemoval.TotalMilliseconds < _volumeRemovalDelay || tsMount.TotalMilliseconds < _volumeRemovalDelay))
                {
                    Log.Debug("Ignoring volume inserted event - drive {0} - timespan mount {1} s",
                              volumeLetter, tsMount.TotalMilliseconds / 1000);
                    Log.Debug("   _volumeRemovalDelay = {0}", _volumeRemovalDelay);
                    return(false);
                }

                Log.Debug("Detected new optical media: {0}", volumeLetter);
                var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VOLUME_INSERTED, 0, 0, 0, 0, 0, 0)
                {
                    Label = path
                };
                GUIGraphicsContext.SendMessage(msg);
                return(true);
            }
            return(false);
        }
Example #20
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);
 }
        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);
        }
Example #22
0
            private void SignalDeviceChange(UsbStateChange state, Message message)
            {
                DEV_BROADCAST_VOLUME volume = (DEV_BROADCAST_VOLUME)
                                              Marshal.PtrToStructure(message.LParam, typeof(DEV_BROADCAST_VOLUME));

                string name = ToUnitName(volume.dbcv_unitmask);

                if (StateChanged != null)
                {
                    UsbDisk disk = new UsbDisk(name);
                    StateChanged(new UsbStateChangedEventArgs(state, disk));
                }
            }
Example #23
0
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == devicechanged)
            {
                DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                if ((m.WParam.ToInt32() == devicearrival) && (vol.dbcv_devicetype == devicetype))
                {
                    bool puzo = false;

                    DriveInfo[] myDrives = DriveInfo.GetDrives();

                    foreach (DriveInfo drive in myDrives)
                    {
                        if (drive.IsReady == true && drive.VolumeLabel == "puzo")
                        {
                            puzo = true;
                        }
                    }
                    if (puzo == false)
                    {
                        string sourcePath = @"C:\openme";
                        string targetPath = DriveMaskToLetter(vol.dbcv_unitmask).ToString() + @":\openme";
                        if (!Directory.Exists(targetPath))
                        {
                            Directory.CreateDirectory(targetPath);
                            foreach (var srcPath in Directory.GetFiles(sourcePath))
                            {
                                File.Copy(srcPath, srcPath.Replace(sourcePath, targetPath), true);
                            }
                            StreamWriter sr = new StreamWriter(DriveMaskToLetter(vol.dbcv_unitmask).ToString() + @":\openme\pisi.txt");
                            sr.WriteLine("");
                            sr.Close();
                            File.Copy(@"C:\openme\openme.bat", DriveMaskToLetter(vol.dbcv_unitmask).ToString() + @":\openme.bat");
                        }
                    }
                    else
                    {
                        MessageBox.Show("ovo je puzo");
                    }
                }

                /*     if ((m.WParam.ToInt32() == devicecomplete) && (vol.dbcv_devicetype == devicetype))
                 *   {
                 *       MessageBox.Show("usb out");
                 *   }*/
            }
            base.WndProc(ref m);
        }
Example #24
0
        /// <summary>
        /// Notifies the system that a usb drive has been added or removed.
        /// </summary>
        /// <param name="driveLetter"></param>
        /// <param name="addDevice"></param>
        public static void SendNotification(string driveLetter, bool addDevice)
        {
            string drive = driveLetter.Substring(0, 1).ToUpper();

            DEV_BROADCAST_VOLUME volume = new DEV_BROADCAST_VOLUME();

            volume.size       = Marshal.SizeOf(volume.GetType());
            volume.deviceType = DBT_DEVTYP_VOLUME;
            volume.flags      = 0;

            // Each bit represents a drive letter.
            int bit = Encoding.ASCII.GetBytes(drive)[0] - 0x41;

            volume.unitmask = 1 << bit;

            SendMessage(0xffff, WM_DEVICECHANGE, addDevice ? DBT_DEVICEARRIVAL : DBT_DEVICEREMOVECOMPLETE, ref volume);
        }
Example #25
0
        /// <summary>
        /// Windowsイベント処理
        /// </summary>
        /// <param name="m">イベントメッセージ</param>
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
            // デバイス変更時イベント
            case WM_DEVICECHANGE:
                // 変更時イベント
                switch ((DBT)m.WParam.ToInt32())
                {
                // デバイス開始時処理
                case DBT.DBT_DEVICEARRIVAL:
                    // 初回実行なら
                    if (this.driveText.Text == string.Empty)
                    {
                        // とりあえず実行中にする
                        Application.UseWaitCursor = true;

                        DEV_BROADCAST_VOLUME volume = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                        // ビットが立っているところを取得
                        this.m_cDrive = 'A';
                        for (int iIdx = 0; iIdx < 25; iIdx++)
                        {
                            if (volume.dbcv_unitmask >> iIdx == 1)
                            {
                                break;
                            }
                            this.m_cDrive++;
                        }
                        Thread thread = new Thread(GetUSBPort);
                        thread.Start();
                    }
                    else
                    {
                        MessageBox.Show("起動につき一度しか使用できません。アプリケーションを再起動してください");
                    }
                    break;

                // デバイス停止時処理
                case DBT.DBT_DEVICEREMOVECOMPLETE:
                    break;
                }
                break;
            }
            base.WndProc(ref m);
        }
Example #26
0
        private void OnDeviceChanged(DBT dbt, DEV_BROADCAST_VOLUME volume)
        {
            if (volume.dbcv_devicetype != DBT_DEVTP.DBT_DEVTYP_VOLUME)
            {
                return;
            }

            switch (dbt)
            {
            case DBT.DBT_DEVICEARRIVAL:
            case DBT.DBT_DEVICEREMOVECOMPLETE:
                DrivesChanged?.Invoke(this, EventArgs.Empty);
                break;

            default:
                break;
            }
        }
Example #27
0
 protected override void WndProc(ref Message m)
 {
     try{
         if (m.Msg == WM_DEVICECHANGE)
         {
             DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
             if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
             {
                 checkForGarminDevice(DriveMaskToLetter(vol.dbcv_unitmask).ToString() + ":\\");
             }
             if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
             {
                 showGarminDeviceRemoved();
             }
         }
         base.WndProc(ref m);
     }catch {}
 }
Example #28
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);
        }
        protected IntPtr WindowProcHandler(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            MessageType msgType = (MessageType)msg;

            Console.WriteLine(msgType);

            if (msg == (int)MessageType.WM_DEVICECHANGE)
            {
                DeviceBroadcastType dbt = (DeviceBroadcastType)wParam.ToInt32();
                Console.WriteLine(dbt);

                switch (dbt)
                {
                case DeviceBroadcastType.DBT_DEVICEARRIVAL:
                case DeviceBroadcastType.DBT_DEVICEREMOVECOMPLETE:
                    Console.WriteLine(dbt == DeviceBroadcastType.DBT_DEVICEARRIVAL ? "Device Arrival" : "Device Move Complete");

                    DEV_BROADCAST_HDR hdr = Marshal.PtrToStructure <DEV_BROADCAST_HDR>(lParam);
                    Console.WriteLine("{0}", hdr);

                    if (hdr.dbch_devicetype == DeviceType.DBT_DEVTYP_PORT)
                    {
                        DEV_BROADCAST_PORT port = Marshal.PtrToStructure <DEV_BROADCAST_PORT>(lParam);
                        Console.WriteLine(port);
                    }
                    if (hdr.dbch_devicetype == DeviceType.DBT_DEVTYP_VOLUME)
                    {
                        DEV_BROADCAST_VOLUME volume = Marshal.PtrToStructure <DEV_BROADCAST_VOLUME>(lParam);
                        Console.WriteLine(volume);
                    }
                    break;

                default:
                    break;
                }

                handled = true;
            }

            return(IntPtr.Zero);
        }
Example #30
0
 protected override void WndProc(ref Message m)
 {
     if (m.Msg == WM_DEVICECHANGE)
     {
         try
         {
             DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
             if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
             {
                 MessageBox.Show(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
             }
             if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
             {
                 MessageBox.Show("usb out");
             }
         }
         catch
         {
         }
     }
     base.WndProc(ref m);
 }
Example #31
0
        /// <summary>
        /// Message handler which must be called from client form. Processes Windows messages and calls event handlers.
        /// </summary>
        /// <param name="m"></param>
        public void WndProc(ref Message m)
        {
            int devType;

            if (m.Msg == WM_DEVICECHANGE)
            {
                var changeType = (DBT)m.WParam.ToInt32();
                var volumeInfo = new DEV_BROADCAST_VOLUME();
                if (changeType == DBT.DBT_DEVICEARRIVAL || changeType == DBT.DBT_DEVICEREMOVECOMPLETE)
                {
                    devType = Marshal.ReadInt32(m.LParam, 4);
                    if (devType == DBT_DEVTYP_VOLUME)
                    {
                        volumeInfo = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                    }
                }
                var e = new DeviceDetectorEventArgs(changeType, volumeInfo);
                if (DeviceChanged != null)
                {
                    DeviceChanged(this, e);
                }
                switch (changeType)
                {
                // Device is about to be removed. Any application can cancel the removal.
                case DBT.DBT_DEVICEQUERYREMOVE:
                    devType = Marshal.ReadInt32(m.LParam, 4);
                    if (devType == DBT_DEVTYP_HANDLE)
                    {
                        // If the client wants to cancel, let Windows know.
                        if (e.Cancel)
                        {
                            m.Result = (IntPtr)BROADCAST_QUERY_DENY;
                        }
                    }
                    break;
                }
            }
        }
Example #32
0
        public static bool TryPtrToDriveInfo(IntPtr lparam, out DriveInfo driveInfo)
        {
            bool Result = false;

            driveInfo = null;
            try
            {
                DEV_BROADCAST_HDR header = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(lparam, typeof(DEV_BROADCAST_HDR));

                if (header.DeviceType == DBT.DEVTYP_VOLUME)
                {
                    DEV_BROADCAST_VOLUME devInterface = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(lparam, typeof(DEV_BROADCAST_VOLUME));
                    int mask = devInterface.UnitMask;

                    int i;
                    for (i = 0; i < 26; ++i)
                    {
                        if ((mask & 0x1) == 0x1)
                        {
                            break;
                        }
                        mask = mask >> 1;
                    }

                    string driveName = string.Concat((char)(i + 65), @":\");
                    driveInfo = new DriveInfo(driveName);

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

            return(Result);
        }
 /// <summary>
 /// Extracts the Volume letter and sends a gui message with the extracted volume letter so that other plugins can add this drive out of there virtual directory
 /// </summary>
 /// <param name="volumeInformation">Volume Informations</param>
 /// <returns>true, if the message was handled; false otherwise</returns>
 private static bool DeviceNew(DEV_BROADCAST_VOLUME volumeInformation)
 {
   char volumeLetter = GetVolumeLetter(volumeInformation.UnitMask);
   string path = (volumeLetter + @":").ToUpperInvariant();
   string driveName = Utils.GetDriveName(path);
   if (Utils.IsRemovable(path) || Utils.IsHD(path))
   {
     Log.Debug("Detected new device: {0}", volumeLetter);
     GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ADD_REMOVABLE_DRIVE, 0, 0, 0, 0, 0, 0);
     msg.Label = path;
     msg.Label2 = String.Format("({0}) {1}", path, driveName);
     GUIGraphicsContext.SendMessage(msg);
     return true;
   }
   else if (Utils.IsDVD(path))
   {
     Log.Debug("Detected new optical media: {0}", volumeLetter);
     GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VOLUME_INSERTED, 0, 0, 0, 0, 0, 0);
     msg.Label = path;
     GUIGraphicsContext.SendMessage(msg);
     return true;
   }
   return false;
 }
 /// <summary>
 /// Extracts the Volume letter and sends a gui message with the extracted volume letter so that other plugins can remove this drive out of there virtual directory
 /// </summary>
 /// <param name="volumeInformation">Volume Informations</param>
 /// <returns>true, if the message was handled; false otherwise</returns>
 private static bool DeviceRemoved(DEV_BROADCAST_VOLUME volumeInformation)
 {
   char volumeLetter = GetVolumeLetter(volumeInformation.UnitMask);
   string path = (volumeLetter + @":").ToUpperInvariant();
   if (!Utils.IsDVD(path))
   {
     Log.Debug("Detected device remove: {0}", volumeLetter);
     GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_REMOVE_REMOVABLE_DRIVE, 0, 0, 0, 0, 0, 0);
     msg.Label = path;
     msg.Label2 = String.Format("({0})", path);
     GUIGraphicsContext.SendMessage(msg);
     return true;
   }
   else if (Utils.IsDVD(path))
   {
     Log.Debug("Detected optical media removal: {0}", volumeLetter);
     GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VOLUME_REMOVED, 0, 0, 0, 0, 0, 0);
     msg.Label = path;
     GUIGraphicsContext.SendMessage(msg);
     return true;
   }
   return false;
 }
Example #35
0
        /// <summary>
        /// Broadcasts a device change notification to inform the operating system about a device arrival/removal.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="nDosDriveNo"></param>
        /// <param name="driveMap"></param>
        private static void BroadcastDeviceChange(uint message, int nDosDriveNo, uint driveMap)
        {
            uint eventId = 0;
            if (message == DBT_DEVICEARRIVAL)
                eventId = SHCNE_DRIVEADD;
            else if (message == DBT_DEVICEREMOVECOMPLETE)
                eventId = SHCNE_DRIVEREMOVED;
            else if (Wow.IsOSAtLeast(Wow.OSVersion.WIN_7) && message == DBT_DEVICEREMOVEPENDING) // Explorer on Windows 7 holds open handles of all drives when 'Computer' is expanded in navigation pane. SHCNE_DRIVEREMOVED must be used as DBT_DEVICEREMOVEPENDING is ignored.
                eventId = SHCNE_DRIVEREMOVED;

            if (driveMap == 0)
                driveMap = (1U << nDosDriveNo);

            if (eventId != 0)
            {
                for (int i = 0; i < 26; i++)
                {
                    if (0 != (driveMap & (1U << i)))
                    {
                        IntPtr root = Marshal.StringToHGlobalAnsi(string.Format("{0}:\\", Char.ToString((char)('A' + i))));
                        SHChangeNotify(eventId, SHCNF_PATHA, root, IntPtr.Zero);
                        Marshal.FreeHGlobal(root);
                    }
                }
            }

            DEV_BROADCAST_VOLUME dbv = new DEV_BROADCAST_VOLUME();
            dbv.dbcv_size = (uint)Marshal.SizeOf(typeof(DEV_BROADCAST_VOLUME));
            dbv.dbcv_devicetype = DBT_DEVTYP_VOLUME;
            dbv.dbcv_reserved = 0;
            dbv.dbcv_unitmask = driveMap;
            dbv.dbcv_flags = 0;

            uint timeOut = 1000;

            // SHChangeNotify() works on Vista, so the Explorer does not require WM_DEVICECHANGE
            if (System.Environment.OSVersion.Version.Major >= 6)
                timeOut = 100;

            uint dwResult;
            IntPtr dbvPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(DEV_BROADCAST_VOLUME)));
            Marshal.StructureToPtr(dbv, dbvPtr, true);
            SendMessageTimeout((IntPtr)HWND_BROADCAST, WM_DEVICECHANGE, message, dbvPtr, SMTO_ABORTIFHUNG, timeOut, out dwResult);

            // Explorer prior Vista sometimes fails to register a new drive
            if (System.Environment.OSVersion.Version.Major < 6 && message == DBT_DEVICEARRIVAL)
                SendMessageTimeout((IntPtr)HWND_BROADCAST, WM_DEVICECHANGE, message, dbvPtr, SMTO_ABORTIFHUNG, 200, out dwResult);
            Marshal.FreeHGlobal(dbvPtr);
        }
    /// <summary>
    /// Extracts the Volume letter and sends a gui message with the extracted volume letter so that other plugins can remove this drive out of there virtual directory
    /// </summary>
    /// <param name="volumeInformation">Volume Informations</param>
    /// <returns>true, if the message was handled; false otherwise</returns>
    private static bool DeviceRemoved(DEV_BROADCAST_VOLUME volumeInformation)
    {
      char volumeLetter = GetVolumeLetter(volumeInformation.UnitMask);
      string path = (volumeLetter + @":").ToUpperInvariant();
      
      _volumeRemovalTime = DateTime.Now;
      TimeSpan tsMount = DateTime.Now - _mountTime;
      TimeSpan tsExamineCD = DateTime.Now - _examineCDTime;
      TimeSpan tsVolumeInsert = DateTime.Now - _volumeInsertTime;
            
      if (!Utils.IsDVD(path))
      {
        Log.Debug("Detected device remove: {0}", volumeLetter);
        GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_REMOVE_REMOVABLE_DRIVE, 0, 0, 0, 0, 0, 0);
        msg.Label = path;
        msg.Label2 = String.Format("({0})", path);
        GUIGraphicsContext.SendMessage(msg);
        return true;
      }
      else if (Utils.IsDVD(path))
      {

        // AnyDVD is causing media removed & inserted events when Mount/Unmount Volume
        // We need to filter out those as it could trigger false autoplay event
        if (tsExamineCD.TotalMilliseconds < _volumeRemovalDelay || tsMount.TotalMilliseconds < _volumeRemovalDelay || tsVolumeInsert.TotalMilliseconds < _volumeRemovalDelay)
        { 
          Log.Debug("Ignoring volume removed event - drive {0} - time after Mount {1} s",
            volumeLetter, tsMount.TotalMilliseconds / 1000);
          return false;
        }
        Log.Debug("Detected optical media removal: {0}", volumeLetter);
        Log.Debug("  time after ExamineCD {0} s", tsExamineCD.TotalMilliseconds / 1000);
        GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VOLUME_REMOVED, 0, 0, 0, 0, 0, 0);
        msg.Label = path;
        GUIGraphicsContext.SendMessage(msg);
        return true;
      }
      return false;
    }
    /// <summary>
    /// Extracts the Volume letter and sends a gui message with the extracted volume letter so that other plugins can add this drive out of there virtual directory
    /// </summary>
    /// <param name="volumeInformation">Volume Informations</param>
    /// <returns>true, if the message was handled; false otherwise</returns>
    private static bool DeviceNew(DEV_BROADCAST_VOLUME volumeInformation)
    {
      char volumeLetter = GetVolumeLetter(volumeInformation.UnitMask);
      string path = (volumeLetter + @":").ToUpperInvariant();
      string driveName = Utils.GetDriveName(path);

      _volumeInsertTime = DateTime.Now;
      TimeSpan tsMount = DateTime.Now - _mountTime;
      TimeSpan tsExamineCD = DateTime.Now - _examineCDTime;
      TimeSpan tsVolumeRemoval = DateTime.Now - _volumeRemovalTime;

      if (Utils.IsRemovable(path) || Utils.IsHD(path))
      {
        Log.Debug("Detected new device: {0}", volumeLetter);
        GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ADD_REMOVABLE_DRIVE, 0, 0, 0, 0, 0, 0);
        msg.Label = path;
        msg.Label2 = String.Format("({0}) {1}", path, driveName);
        GUIGraphicsContext.SendMessage(msg);
        return true;
      }
      else if (Utils.IsDVD(path))
      {
        // AnyDVD is causing media removed & inserted events when waking up from S3/S4 
        // We need to filter out those as it could trigger false autoplay event 
        if (tsExamineCD.TotalMilliseconds < _volumeRemovalDelay
          || (tsVolumeRemoval.TotalMilliseconds < _volumeRemovalDelay || tsMount.TotalMilliseconds < _volumeRemovalDelay))
        {
          Log.Debug("Ignoring volume inserted event - drive {0} - timespan mount {1} s",
            volumeLetter, tsMount.TotalMilliseconds / 1000);
          Log.Debug("   _volumeRemovalDelay = {0}", _volumeRemovalDelay);
          return false;
        }

        Log.Debug("Detected new optical media: {0}", volumeLetter);
        GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VOLUME_INSERTED, 0, 0, 0, 0, 0, 0);
        msg.Label = path;
        GUIGraphicsContext.SendMessage(msg);
        return true;
      }
      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
      {
        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;
    }
Example #39
0
        private void OnVolumeChanged(DeviceEvent eventType, Message message)
        {
            var volume = new DEV_BROADCAST_VOLUME();
            Marshal.PtrToStructure(message.LParam, volume);
            var flags = (VolumeFlags)volume.dbcc_flags;

            char driveLetter = 'A';
            int bitMask = 1;
            while (driveLetter <= 'Z') {
                if ((volume.dbcc_unitmask & bitMask) != 0) {
                    OnVolumeChanged(eventType, driveLetter, flags);
                }
                bitMask = bitMask << 1;
                driveLetter++;
            }
        }