c++ Qt windows 弹出盘符

22 篇文章 0 订阅

 在已知盘符的情况下弹出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;

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值