简体   繁体   中英

How to detect a USB HDD programatically using c#

Hi I have to develop an app that detects a USB HDD using C#. Is it possible?. I have a code for detecting a USB Mass storage device. I added reference to System.Runtime.InteropServices I tried to override WndProc() method. I will include the snippet

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:
       MessageBox.Show(
      string.Format("A storage device has been inserted; Drive :{0}", ToDriveName(volume.dbcv_unitmask)), "Detect USB");
      break;

   // Device Removed.
   case DBT_DEVICEREMOVECOMPLETE:
        MessageBox.Show("Storage has been removed.", "Detect USB");
        break;
     }
   }
 }
}

I developed an application for the USB Pen drives below is my declarations:

        const int WM_DEVICECHANGE = 0x0219;
        const int DBT_DEVICEARRIVAL = 0x8000;
        const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
        const int DBT_DEVTYPVOLUME = 0x00000002;

Below is my override of WinProc :

        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))
                    {
                        usb_drive = DriveMaskToLetter(vol.dbcv_unitmask).ToString();

                        if (usb_drive.Replace(" ", "").Length > 0)
                        {

                            // USB Inserted                                  
                        }
                    }
                    if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
                    {
                        //USB Removed
                    }
                }
                base.WndProc(ref m);
            }
            catch
            {

            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM