How do I Prevent Explorer Windows from Opening on WM_DEVICECHANGE?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I have the following handy bit of code to help notify me when a device is plugged into the computer...
<pre class="prettyprint public class DriveDetector : NativeWindow
{
public event DriveDetectedEventHandler DriveDetected;
public delegate void DriveDetectedEventHandler(object sender, DriveDetectedEventArgs e);

public const int WM_DEVICECHANGE = 0x219;

public const int DBT_DEVICEARRIVAL = 0x8000;
public const int DBT_DEVICEQUERYREMOVE = 0x8001;
public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
public const int DBT_DEVTYP_VOLUME = 0x2;

[StructLayout(LayoutKind.Sequential)]
private struct DEV_BROADCAST_VOLUME
{
public Int32 dbcv_size;
public Int32 dbcv_devicetype;
public Int32 dbcv_reserved;
public Int32 dbcv_unitmask;
public Int16 dbcv_flags;
}

public DriveDetector()
{
CreateHandle(new CreateParams());
}

protected override void WndProc(ref Message m)
{
Debug.Print(m.Msg.ToString());

if (m.Msg == WM_DEVICECHANGE)
{
switch (m.WParam.ToInt32())
{
case DBT_DEVICEARRIVAL:
if ((Marshal.ReadInt32(m.LParam, 4) == DBT_DEVTYP_VOLUME))
{
DEV_BROADCAST_VOLUME volumeDevice = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));

DriveDetectedEventArgs eventArgs = new DriveDetectedEventArgs
{
DriveLetter = MaskDriveLetter(volumeDevice.dbcv_unitmask),
DriveSerial = &quot;Nothing&quot;

};
if (DriveDetected != null)
{
DriveDetected(this, eventArgs);
}
}
break;
}
}

base.WndProc(ref m);
}

private char MaskDriveLetter(int driveMask)
{
int count = 0;
dynamic index = driveMask &gt;&gt; 1;
while ((index &gt; 0))
{
index &gt;&gt;= 1;
count &#43;= 1;
}
return &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;[count];
}


}[/code]
It all works great, and does what I need, however I keep having the File Explorer window opening each time the device, which happens to be a USB stick, as plugged in. 
Using the scenario code above, how do I prevent the explorer window from opening?
<
PP

View the full article
 
Back
Top