目录
1 概述
本文描述了在Qt下利用Windows API实现U盘及光盘弹出操作。
2 实现
通过查资料U盘弹出操作需要使用Windows API函数CM_Request_Device_Eject,该函数原型为:
CMAPI CONFIGRET CM_Request_Device_Eject(
[in] DEVINST dnDevInst,
[out, optional] PPNP_VETO_TYPE pVetoType,
[out, optional] LPWSTR pszVetoName,
[in] ULONG ulNameLength,
[in] ULONG ulFlags
);
实现关键是如何将U盘的驱动器盘符转化为DEVINST类型设备句柄。
需要引用的Windows API头文件
#include <windows.h>
#include <winioctl.h>
#include <setupapi.h>
#include <initguid.h>
#include <newdev.h>
#include <cfgmgr32.h>
#include <regstr.h>
#include <combaseapi.h>
#include <shlobj.h>
2.1 函数定义
定义下面5个函数实现磁盘弹出:
- GetDiskNumber 通过驱动器名称返回磁盘号
- GetDriverType 通过驱动器名称返回类型
- GetDrivesDevInstByDiskNumber 通过驱动器号和类型返回磁盘设备号
- IsRemovable 通过设备号判断磁盘是否可移出
- RemoveDisk 通过驱动器号和类型弹出磁盘
- EjectDisk 通过驱动器名称弹出磁盘
2.2 函数实现
2.2.1 GetDiskNumber
long GetDiskNumber(QString const& dirverPath, bool isDevicePath = false)
{
long diskNumber = -1;
QString volumeAccessPath = isDevicePath ? dirverPath : QString("\\\\.\\%1").arg(dirverPath.toUpper());
HANDLE hVolume = CreateFile(volumeAccessPath.toStdWString().c_str(), 0,
FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if(hVolume == INVALID_HANDLE_VALUE)
return diskNumber;
STORAGE_DEVICE_NUMBER sdn;
DWORD dwBytesReturned = 0;
long res = DeviceIoControl(hVolume, IOCTL_STORAGE_GET_DEVICE_NUMBER

1021

被折叠的 条评论
为什么被折叠?



