Qt listens for USB device insertion and Removal

Source: Internet
Author: User

Refer to online materials and use QT to implement


#ifndef WIDGET_H#define WIDGET_H #include <QtGui/QWidget>#include <windows.h>#include <QString> class Widget : public QWidget{Q_OBJECT public:Widget(QWidget *parent = 0);~Widget(); protected:bool winEvent(MSG *msg, long *result); private://UsbConfig usbConfig;char FirstDriveFromMask (ULONG unitmask);}; #endif // WIDGET_H



# Include "qt_watch/qwidget. H "# include <qdebug> # include <windows. h> # include <DBT. h> Widget: widget (qwidget * parent): qwidget (parent) {setwindowflags (QT: Window); // window uses window as the parent window} Widget ::~ Widget () {} bool Widget: winevent (MSG * MSG, long * result) {int msgtype = MSG-> message; If (msgtype = wm_devicechange) {qdebug () <"receive event"; pdev_broadcast_hdr lpdb = (pdev_broadcast_hdr) MSG-> lparam; Switch (MSG-> wparam) {Case dbt_devicetypespecpacific: {qdebug () <"Warn "; break;} case dbt_devicearrival: If (lpdb-> dbch_devicetype = dbt_devtyp_volume) {pdev_broadcast_volume lpdbv = (bytes) lpdb; if) {// insert a USB flash drive. Here you can do what you want to do: qstring usbdisk = qstring (this-> firstdrivefrommask (lpdbv-> dbcv_unitmask); qdebug () <"usb_arrived and the usbdisk is:" <usbdisk ;}} qdebug () <"dbt_devicearrival"; break; case when: If (lpdb-> dbch_devicetype = dbt_devtyp_volume) {pdev_broadcast_volume lpdbv = (pdev_broadcast_volume) lpdb; If (lpdbv-> dbcv_flags = 0) {qdebug () <"USB _ DEVICE removal" ;}} qdebug () <"dbt_deviceremovecomplete"; break ;}return false;} Char Widget: firstdrivefrommask (ulong unitmask) {char I; for (I = 0; I <26; ++ I) {If (unitmask & 0x1) break; unitmask = unitmask> 1 ;}return (I + 'A ');}

#include <QApplication>#include "qt_Watch/qwidget.h"int main(int argc,char ** argv){QApplication app(argc,argv);Widget widget;widget.show();return app.exec();}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.