How To detect USB plug and play

.NET programming topics
Post Reply
User avatar
Enigma
Lieutenant
Lieutenant
Posts: 74
Joined: Sun Jan 16, 2011 12:40 am
Location: Colombo, Sri Lanka

How To detect USB plug and play

Post by Enigma » Fri Mar 23, 2012 4:01 pm

Hi guys
I have been inactive some time now.Sorry for that. Anyway one of my teammate asked how to detect USB flash drive from C#. So here goes another flash drive detector.

Code: Select all

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;

namespace FlashDriveTest
{

    //msdn:http://msdn.microsoft.com/en-us/library/aa363246.aspx
    //structure will expose device type
    [StructLayout(LayoutKind.Sequential)]
    struct DEV_BROADCAST_HDR
    {
        public uint dbch_Size;
        public uint dbch_DeviceType;
        public uint dbch_Reserved;
    }


    //msdn:http://msdn.microsoft.com/en-us/library/aa363249.aspx
    //this structre will expose volume information
    [StructLayout(LayoutKind.Sequential)]
    struct _DEV_BROADCAST_VOLUME
    {
        public uint dbcv_size;
        public uint dbcv_devicetype;
        public uint dbcv_reserved;
        public uint dbcv_unitmask;
        public int dbcv_flags;
    }



    public partial class frmFlashTest : Form
    {
        //msdn:http://msdn.microsoft.com/en-us/library/aa363480.aspx
        private const int WM_DEVICECHANGE = 0x219;

        //msdn:http://msdn.microsoft.com/en-us/library/aa363205.aspx
        private const int DBT_DEVICEARRIVAL = 0x8000;

        //msdn:http://msdn.microsoft.com/en-us/library/aa363208.aspx
        private const int DBT_DEVICEREMOVECOMPLETE = 0x8004;

        //msdn:http://msdn.microsoft.com/en-us/library/aa363246.aspx
        private const int DBT_DEVTYP_VOLUME = 0x00000002;

        //msdn:http://msdn.microsoft.com/en-us/library/aa363246.aspx
        private const int DBT_DEVTYP_PORT = 0x00000003;

        public frmFlashTest()
        {
            InitializeComponent();
        }

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                //catching any system device change
                case WM_DEVICECHANGE:
                    {
                        //check for device insertion
                        if (m.WParam == (IntPtr)DBT_DEVICEARRIVAL)
                        {
                            DEV_BROADCAST_HDR dev_bcast = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));

                            //if inserted device is a Logical volume then
                            if (dev_bcast.dbch_DeviceType == DBT_DEVTYP_VOLUME)
                            {
                                _DEV_BROADCAST_VOLUME dev_vol = (_DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(_DEV_BROADCAST_VOLUME));

                                //get the volume info
                                DriveInfo flash = this.GetVolume(dev_vol.dbcv_unitmask);

                                lbldvol.Text = lbldvol.Text + ":" + flash.Name;
                                long spce =(long)((flash.TotalSize/1024)/1024);
                                lblspc.Text = lblspc.Text+":"+spce.ToString()+" MB";
                                lblStatus.Text = lblStatus.Text+":"+flash.IsReady.ToString();
                                lbltyp.Text = lbltyp.Text + ":" + flash.DriveType.ToString();
                                spce = (long)((flash.TotalFreeSpace / 1024) / 1024);
                                lblavl.Text = lblavl.Text+":" + spce.ToString() + " MB";
                                lblfrmt.Text = lblfrmt.Text + ":" + flash.DriveFormat;
                                lblVolLable.Text =lblVolLable+Text+":"+ flash.VolumeLabel;
                            }
                        }
                        //if a device got removed
                        else if (m.WParam == (IntPtr)DBT_DEVICEREMOVECOMPLETE)
                        {
                            DEV_BROADCAST_HDR dev_bcast = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                            if (dev_bcast.dbch_DeviceType == DBT_DEVTYP_VOLUME)
                            {
                                _DEV_BROADCAST_VOLUME dev_vol = (_DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(_DEV_BROADCAST_VOLUME));
                                //get the removed volume info
                                DriveInfo flash = this.GetVolume(dev_vol.dbcv_unitmask);

                                MessageBox.Show(flash.Name + " has removed from the system");
                                lbldvol.Text = "Driver Volume";
                                lblspc.Text = "Total Space";
                                lblStatus.Text = "Is Connected";
                                lbltyp.Text = "Type";
                                lblavl.Text = "Available Space";
                                lblfrmt.Text = "Format";
                                lblVolLable.Text = "Volume Label";
                            }
                        }
                       
                        break;
                    }
            }

            base.WndProc(ref m);
        }

        //if the bit mask is 1000 then 1- means drive A, 0-means drive B, again 0-means drive C. likewise 
        //we can get the volume label
        private DriveInfo GetVolume(uint Mask)
        {
            string[] volumes = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "k", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
            string bin = Convert.ToString(Mask, 2);
            string volume = volumes[bin.Length - 1];
            DriveInfo dinf = new DriveInfo(volume);
            return dinf;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

Code is commented well and I'm attaching the VS2010 solution with this. Click here
FlashDriveTest.zip
(47.49 KiB) Downloaded 467 times
to download it. Feel free to improve this as you like. Cheeers :)

Thanks
Enigma
Post Reply

Return to “.NET Programming”