在已知盘符的情况下弹出U盘。
QString device_path = "F:\";
QString error_string;
const char* temp = "\\\\.\\";
char device_path1[10] = { 0 };
memcpy(device_path1, temp, strlen(temp));
QByteArray dp = device_path.toLocal8Bit();
device_path1[4] = dp.at(0);
device_path1[5] = dp.at(1);
HANDLE handleDevice = CreateFileA(device_path1, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
bool is_handle_invalid = (handleDevice == INVALID_HANDLE_VALUE);
if (is_handle_invalid)
{
error_string = "Device is not connection to system!";
qDebug() << GetLastError();
return false;
}
// Do this in a loop until a timeout period has expired
const int try_lock_volume_count = 3;
int try_count = 0;
for (; try_count < try_lock_volume_count; ++try_count)
{
DWORD dwBytesReturned;
if (!DeviceIoControl(handleDevice, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwBytesReturned, NULL))
{
qDebug() << "Device is using....." << try_count;
break;
}
QThread::sleep(1);
}
if (try_count == try_lock_volume_count)
{
error_string = "Device is using, try again later";
CloseHandle(handleDevice);
return false;
}
DWORD dwBytesReturned = 0;
PREVENT_MEDIA_REMOVAL PMRBuffer;
PMRBuffer.PreventMediaRemoval = FALSE;
if (!DeviceIoControl(handleDevice, IOCTL_STORAGE_MEDIA_REMOVAL, &PMRBuffer, sizeof(PREVENT_MEDIA_REMOVAL), NULL, 0, &dwBytesReturned, NULL))
{
error_string = QStringLiteral("Unmount failed! error code:%1").arg(GetLastError());
qDebug() << "DeviceIoControl IOCTL_STORAGE_MEDIA_REMOVAL failed:" << GetLastError();
CloseHandle(handleDevice);
return false;
}
long bResult = 0;
DWORD retu = 0;
bResult = DeviceIoControl(handleDevice, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, &retu, NULL);
if (!bResult)
{
error_string = QStringLiteral("Disconnect IGU failed! error code:%1").arg(GetLastError());
CloseHandle(handleDevice);
qDebug() << "Disconnect IGU IoControl failed error:" << GetLastError();
return false;
}
CloseHandle(handleDevice);
return true;