Search
Archives
- August 2015 (1)
- September 2014 (1)
- June 2014 (2)
- January 2014 (1)
- September 2012 (1)
- July 2012 (1)
- April 2012 (1)
- January 2012 (2)
- June 2011 (2)
- November 2010 (1)
- October 2010 (1)
- May 2010 (2)
- April 2010 (1)
- December 2009 (1)
- November 2009 (1)
- August 2009 (1)
- June 2009 (1)
- April 2009 (1)
- January 2009 (5)
- December 2008 (1)
- November 2008 (1)
- August 2008 (3)
- July 2008 (3)
- June 2008 (1)
- February 2008 (2)
- January 2008 (1)
- November 2007 (2)
- September 2007 (1)
- July 2007 (1)
- May 2007 (2)
Categories
Meta
Monthly Archives: April 2010
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); } }