Detecting drive insertion and removal in C#

Here is some C# code to detect when a logical volume (e.g. USB Memory Stick) is inserted or removed via the WM_DEVICECHANGE message with WndProc.

However this doesn’t tell you what has been inserted/removed, you will have to poll the drives manually to find out.
If you need that you will have to register to receive events from windows which involves P/Invoking RegisterDeviceNotification (See Drive Detector at Code Project).

[...]
using System.Runtime.InteropServices;
using System.Security.Permissions;

public class MyForm : Form
{
        const int WM_DEVICECHANGE = 0x0219;
        const int DBT_DEVICEARRIVAL = 0x8000; // system detected a new device
        const int DBT_DEVICEREMOVECOMPLETE = 0x8004; //device was removed
        const int DBT_DEVNODES_CHANGED = 0x0007; //device changed
        const int DBT_DEVTYP_VOLUME = 0x00000002; // logical volume

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICECHANGE
                && m.WParam.ToInt32() == DBT_DEVICEARRIVAL
                || m.WParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE
                || m.WParam.ToInt32() == DBT_DEVNODES_CHANGED))
            {
                if (m.WParam.ToInt32() != DBT_DEVNODES_CHANGED)
                {
                    int devType = Marshal.ReadInt32(m.LParam, 4);
                    if (devType == DBT_DEVTYP_VOLUME)
                    {
                        //Poll drives
                    }
                }
                else
                {
                    //Poll drives
                }
            }

            base.WndProc(ref m);
        }
}
Bookmark the permalink.

Leave a Reply

Your email address will not be published.