vc弹出USB的方法. 附试验通过的代码!
http://blog.sina.com.cn/s/blog_4fcd1ea30100qrzn.html
(2011-04-15 10:09:48)bool CUsbSwitchDlg::UnInstallUsb(char szDriveName) //参数是要弹出的盘符如:G,F
{
DWORD accessMode = 0, shareMode = 0;
HANDLE hDevice;
ULONG returned = 0,bResult = 0;
DWORD dwError;
shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; // default
accessMode = GENERIC_WRITE | GENERIC_READ; // default
if (szDriveName == 0)
{
return FALSE;
}
CString vol_string = \\.\G:;
vol_string.SetAt(4, szDriveName);
hDevice = CreateFile(vol_string,
accessMode, shareMode, NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
CString debugInfo;
dwError = GetLastError();
debugInfo.Format("error = %d ", dwError);
TRACE("IOCTL_STORAGE_EJECT_MEDIA errorcode = %d ", dwError);
return FALSE;
}
bResult = DeviceIoControl(hDevice,
IOCTL_STORAGE_EJECT_MEDIA, //弹出U盘的具体命令。
NULL, 0, NULL, 0,&returned, NULL);
if (!bResult) // IOCTL failed //经实验,有时虽然失败了,U盘还是能弹出
{
CString debugInfo;
dwError = GetLastError();
debugInfo.Format("error = %d ", dwError);
TRACE("IOCTL_STORAGE_EJECT_MEDIA errorcode = %d ", dwError);
}
bResult = CloseHandle(hDevice);
if (!bResult)
{
CString debugInfo;
dwError = GetLastError();
debugInfo.Format("error = %d ", dwError);
TRACE("IOCTL_STORAGE_EJECT_MEDIA errorcode = %d ", dwError);
return FALSE;
}
return TRUE;
}
关于U盘盘符的问题:
添加WM_DEVICECHANGE的消息处理函数OnDeviceChange,
在该函数中捕获DBT_DEVICEARRIVAL事件(当U盘插入时,OS会发WM_DEVICECHANGE广播消息,该消息的wParam中会包含DBT_DEVICEARRIVAL事件),
同时得到DEV_BROADCAST_VOLUME结构的数据,DEV_BROADCAST_VOLUME结构的dbch_devicetype 成员是DBT_DEVTYP_VOLUME代表是磁盘。
dbcv_unitmask成员是一个Mask变量,最低位对应A,其次是B,...,根据它可就可以得到当前U盘的盘符了. 比如0x1代表A盘。0x10代表B盘。当然同理你可以得到系统上刚插入的串口设备。要学会举一反三。
BOOL CUsbSwitchDlg::OnDeviceChange( UINT nEventType, DWORD dwData )
{
if (nEventType == DBT_DEVICEARRIVAL)
{
DEV_BROADCAST_HDR* dev_hdr = (DEV_BROADCAST_HDR*)dwData;
if (dev_hdr->dbch_devicetype == DBT_DEVTYP_VOLUME)
{
DEV_BROADCAST_VOLUME* pdev_vol = (DEV_BROADCAST_VOLUME*)dwData;;
int vol_char = 0;
int vol_int = pdev_vol->dbcv_unitmask;
// calculate the vol_num
for (;vol_int;)
{
vol_int = vol_int/2;
vol_char++;
}
m_USBvolNum = vol_char + 'A' - 1;//m_USBvolNum即为盘符,如G或者I
}
}
return FALSE;
}