Thursday, March 15, 2012

Check if Removable Devices (like USB Flash Drives) Are Connected Or Disconnected

In the previous post, upon which this post is based, I explained, how to recognize with C#, if the hardware settings of the computer have changed.
This most now focusses on the topic of finding out, if removable mediums, like USB flash drives, got plugged in or plugged off.

Therefor we use the previously introduced event WM_DEVICECHANGE as a notification, when devices are connected or disconnected.
Then we use the enumeration System.IO.DriveInfo.GetDrives(), which contains all drives of the computer, all internal harddrives but also the external flashdrives. Of these devices we now determine the type (DriveType), if this is DriveType.Removable, the currently examined device is a flash drive.
In the function we count the number of these devices and by calculating the difference, we can determine, whether a USB flash drive was connected or disconnected.

I think, the corresponding should be self explaining:

        private void Form1_Load(object sender, EventArgs e)
        {
            CheckDrives();
        }

        int USBCount;

        private void CheckDrives()
        {
            USBCount = 0;
            foreach (System.IO.DriveInfo d in System.IO.DriveInfo.GetDrives())
            {
                if (d.DriveType == System.IO.DriveType.Removable)
                    USBCount++;
            }
        }

        const int WM_DEVICECHANGE = 0x219;
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICECHANGE)
            {
                int OldUSBCount = USBCount;
                CheckDrives();
                if (USBCount > OldUSBCount)
                    MessageBox.Show("USB flash drive connected.");
                if (USBCount < OldUSBCount)
                    MessageBox.Show("USB flash drive disconnected.");
            }

            base.WndProc(ref m);
        }

1 comment: