USB notification detection in Qt on windows

In my qt application, I want to save some application output to a file in my USB drive. I need to add the following functions to my qt application

  • Usb drive insert detection
  • I have only one slot for usb.
  • After I insert it, I want to find out its number and drive letter and transfer the file to a specific location on my PC to this USB drive.

Can someone tell me which winapi.lib, .h and .dll files I have in order to use all of the above functions?

If someone can provide some snippets of code, this will be very helpful to me.

+4
source share
2 answers

WM_DEVICECHANGE handle - see http://lists.trolltech.com/qt-interest/2001-08/thread00698-0.html for handling Windows messages in QT.

If wParam DBT_DEVICEARRIVAL , then drop lParam to DEV_BROADCAST_HDR *

If the dbch_devicetype DBT_DEVTYP_VOLUME structures again outline lParam, this time until DEV_BROADCAST_VOLUME *

Now check the dbcv_unitmask bit dbcv_unitmask , repeat bit 0..31 and check if the corresponding drive matches your USB drive.

 if (wParam == DBT_DEVICEARRIVAL) { if (((DEV_BROADCAST_HDR *) lParam)->dbch_devicetype == DBT_DEVTYP_VOLUME) { DWORD Mask = ((DEV_BROADCAST_VOLUME *) lParam)->dbcv_unitmask; for (int i = 0; i < 32; ++i) { if (Mask & (1 << i)) { char RootPath[4] = "A:\\"; RootPath[0] += i; // Check if the root path in RootPath is your USB drive. } } } } 
+3
source

An earlier answer is now deprecated. The following worked for me with QT5 on Windows 10, where MainWindow is sourced from QMainWindow:

 #include <QByteArray> #include <windows.h> #include <dbt.h> bool MainWindow::nativeEvent(const QByteArray& eventType, void* pMessage, long* pResult) { auto pWindowsMessage = static_cast<MSG*>(pMessage); auto wParam = pWindowsMessage->wParam; if (wParam == DBT_DEVICEARRIVAL || wParam == DBT_DEVICEREMOVECOMPLETE) { auto lParam = pWindowsMessage->lParam; auto deviceType = reinterpret_cast<DEV_BROADCAST_HDR*>(lParam)->dbch_devicetype; if (deviceType == DBT_DEVTYP_VOLUME) { auto unitmask = reinterpret_cast<DEV_BROADCAST_VOLUME*>(lParam)->dbcv_unitmask; for (int i = 0; i < 32; ++i) { if ((unitmask & (1 << i)) != 0) { setDriveChanged('A' + i, wParam == DBT_DEVICEARRIVAL); } } } } return false; } 
+2
source

All Articles