I am working on USB Monitor in C# and I wanted to be able to react after the system driver processed arrival and enabled the arriving device, but faster than application level processes (Explorer). I wanted to examine device for autorun.inf and if found to DENY the arrival. I used BROADCAST_QUERY_DENY as described on MSDN but no success. Here is the code (assuming USB arrives as 'I' drive):
switch (msg.Msg)
{
case Win32CODES.WM_DEVICECHANGE:
{
if (msg.LParam != IntPtr.Zero)
{
DEV_BROADCAST_HDR pHdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(msg.LParam, typeof(DEV_BROADCAST_HDR));
switch ((int)msg.WParam)
{
case Win32CODES.DBT_DEVICEARRIVAL:
{
if (pHdr.dbch_devicetype == Win32CODES.DBT_DEVTYP_VOLUME)
{
DEV_BROADCAST_VOLUME pVol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(msg.LParam, typeof(DEV_BROADCAST_VOLUME));
Char c = GetDriveLetter(pVol.dbcv_unitmask);
if (c == 'I')
{
msg.Result = new IntPtr(Win32CODES.BROADCAST_QUERY_DENY );
base.WndProc(ref msg);
return;
}
}
break;
}
}
}
break;
}
}
base.WndProc(ref msg);
}
Then I tried another way but again no success.
switch (msg.Msg)
{
case Win32CODES.WM_DEVICECHANGE:
{
if (msg.LParam != IntPtr.Zero)
{
DEV_BROADCAST_HDR pHdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(msg.LParam, typeof(DEV_BROADCAST_HDR));
switch ((int)msg.WParam)
{
case Win32CODES.DBT_DEVICEARRIVAL:
{
if (pHdr.dbch_devicetype == Win32CODES.DBT_DEVTYP_VOLUME)
{
DEV_BROADCAST_VOLUME pVol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(msg.LParam, typeof(DEV_BROADCAST_VOLUME));
Char c = GetDriveLetter(pVol.dbcv_unitmask);
if (c == 'I')
{
int bytesReturned = 0;
IntPtr buffer = Marshal.AllocHGlobal(sizeof(int));
SafeFileHandle _hdev = CreateFileR(c.ToString());
bool result = DeviceIoControl(_hdev, CTL_CODE(0x00000033, 0x0400, 0, 1),
IntPtr.Zero, 0, buffer, sizeof(int),
out bytesReturned, IntPtr.Zero);
int sessionId = Marshal.ReadInt32(buffer);
Marshal.FreeHGlobal(buffer);
}
}
break;
}
}
}
break;
}
}
base.WndProc(ref msg);
Is there a way to accomplish this? Thanks..
User contributions licensed under CC BY-SA 3.0