我正在尝试检测何时插入 USB 驱动器。现在,我正在创建一个虚拟窗口并RegisterDeviceNotification
对其进行编译。但是,我认为我的方法不正确,因为窗口似乎没有收到消息。
#include <iostream>
#define WINVER 0x501
#include <windows.h>
#include <dbt.h>
#include "devicehandler.h"
#include "remover.h"
DeviceHandler::DeviceHandler(Remover* remover)
{
this->remover = remover;
this->hWnd = this->createHandleWindow();
this->registerDeviceHandler();
this->messageLoop(this->hWnd);
}
DeviceHandler::~DeviceHandler()
{
this->unregisterDeviceHandler();
}
void DeviceHandler::messageLoop(HWND hWnd)
{
std::cerr << "Entering message loop." << std::endl; // Gets here!
MSG msg;
while (GetMessage(&msg, this->hWnd, 0, 0)) {
std::cerr << "Loop!" << std::endl; // Does not get here!
switch (msg.message) {
case WM_DEVICECHANGE:
{
PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR) msg.lParam;
switch(msg.wParam) {
case DBT_DEVICEARRIVAL:
std::cerr << "Device added!" << std::endl;
break;
default:
std::cerr << "Other device event." << std::endl;
break;
}
break;
}
default:
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
HWND DeviceHandler::createHandleWindow()
{
std::cerr << "Creating handle window... ";
HWND hWnd = CreateWindow(NULL, NULL, WS_ICONIC, 0, 0, CW_USEDEFAULT, 0,
NULL, NULL, GetModuleHandle(NULL), NULL);
ShowWindow(hWnd, SW_HIDE);
std::cerr << "done!" << std::endl;
return hWnd;
}
void DeviceHandler::registerDeviceHandler()
{
std::cerr << "Device notification handling... ";
// GUID guid = { 0xa5dcbf10, 0x6530, 0x11d2, { 0x90, 0x1f, 0x00, 0xc0, 0x4f, 0xb9, 0x51, 0xed } };
GUID guid = { 0x25dbce51, 0x6c8f, 0x4a72, { 0x8a, 0x6d, 0xb5, 0x4c, 0x2b, 0x4f, 0xc8, 0x35 } };
DEV_BROADCAST_DEVICEINTERFACE notificationFilter;
ZeroMemory(¬ificationFilter, sizeof(notificationFilter));
notificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
notificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
notificationFilter.dbcc_classguid = guid;
this->deviceNotifier = RegisterDeviceNotification(this->hWnd,
¬ificationFilter,
DEVICE_NOTIFY_WINDOW_HANDLE);
std::cerr << "done!" << std::endl;
}
void DeviceHandler::unregisterDeviceHandler()
{
UnregisterDeviceNotification(this->deviceNotifier);
}
我猜这不是放置消息循环的正确位置,但我对 WinAPI 不是很好。如何让我的程序进入消息循环?(并且最好注册设备通知。)