Article ID: 163503
Article Last Modified on 5/1/2007
#include <windows.h>
#include <dbt.h>
char FirstDriveFromMask (ULONG unitmask); //prototype
/*----------------------------------------------------------------------
Main_OnDeviceChange (hwnd, wParam, lParam)
Description
Handles WM_DEVICECHANGE messages sent to the application's
top-level window.
----------------------------------------------------------------------*/
void Main_OnDeviceChange (HWND hwnd, WPARAM wParam, LPARAM lParam)
{
PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;
char szMsg[80];
switch(wParam)
{
case DBT_DEVICEARRIVAL:
// See if a CD-ROM or DVD was inserted into a drive.
if (lpdb -> dbch_devicetype == DBT_DEVTYP_VOLUME)
{
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
if (lpdbv -> dbcv_flags & DBTF_MEDIA)
{
wsprintf (szMsg, "Drive %c: arrived\n",
FirstDriveFromMask(lpdbv ->dbcv_unitmask));
MessageBox (hwnd, szMsg, "WM_DEVICECHANGE", MB_OK);
}
}
break;
case DBT_DEVICEREMOVECOMPLETE:
// See if a CD-ROM was removed from a drive.
if (lpdb -> dbch_devicetype == DBT_DEVTYP_VOLUME)
{
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
if (lpdbv -> dbcv_flags & DBTF_MEDIA)
{
wsprintf (szMsg, "Drive %c: was removed\n",
FirstDriveFromMask(lpdbv ->dbcv_unitmask));
MessageBox (hwnd, szMsg, "WM_DEVICECHANGE", MB_OK);
}
}
break;
default:
/*
Other WM_DEVICECHANGE notifications get sent for other devices
or reasons; we don't care about them here. If they were
important, we would check for them and act accordingly.
*/
;
}
}
/*----------------------------------------------------------------------
FirstDriveFromMask (unitmask)
Finds the first valid drive letter from a mask of drive letters. The
mask must be in the format bit 0 = A, bit 1 = B, bit 3 = C, etc.
A valid drive letter is defined when the corresponding bit is set to
1.
Returns the drive letter that was first found.
----------------------------------------------------------------------*/
char FirstDriveFromMask (ULONG unitmask)
{
char i;
for (i = 0; i < 26; ++i)
{
if (unitmask & 0x1)
break;
unitmask = unitmask >> 1;
}
return (i + 'A');
}
Although this sample code only checks for volume arrivals due to the
insertion of new media, it can be extended to get notification of other
hardware events for other types too. To do so, you have to add cases for
other device events and handle different device types for each event.
Additional query words: notify notification cdrom CD-ROM detect
Keywords: kbapi kbcode kbfileio kbhowto kbkernbase KB163503