当我运行我的程序(下面的代码)并通过 USB 电缆插入硬盘驱动器时,WindowProcedure
会调用WM_DEVICECHANGE
device-change event type 的消息DBT_DEVICEARRIVAL
。
然而,GetMessage
不返回。文档GetMessage
说_GetMessage
从调用线程的消息队列中检索消息。
因此,听起来线程的消息队列中没有消息。
为什么我的调用线程的消息队列中没有消息?
如果我的调用线程的消息队列中没有消息,如何/为什么为设备更改事件类型WindowProcedure
的消息调用我的函数?WM_DEVICECHANGE
DBT_DEVICEARRIVAL
注意:我已经阅读了一些相关的帖子和页面。 这个stackoverflow帖子似乎可能是相关的。如果是这样,我怎么知道哪些消息实际放置在消息队列中?
namespace {
LRESULT CALLBACK WindowProcedure(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if( uMsg == WM_DEVICECHANGE )
{
switch(wParam)
{
case DBT_DEVICEARRIVAL:
{
PostQuitMessage('L');
break;
}
case DBT_DEVNODES_CHANGED:
{
break;
}
}
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
}
BOOL DoRegisterDeviceInterfaceToHwnd(IN GUID InterfaceClassGuid, IN HWND hWnd, OUT HDEVNOTIFY *hDeviceNotify)
{
DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
ZeroMemory( &NotificationFilter, sizeof(NotificationFilter) );
NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
NotificationFilter.dbcc_classguid = InterfaceClassGuid;
*hDeviceNotify = RegisterDeviceNotification(
hWnd, // events recipient
&NotificationFilter, // type of device
DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES // type of recipient handle
);
if ( NULL == *hDeviceNotify )
{
//ErrorHandler(TEXT("RegisterDeviceNotification"));
return FALSE;
}
return TRUE;
}
int processWindowsMessages()
{
WNDCLASS windowClass = {};
windowClass.lpfnWndProc = WindowProcedure;
LPCSTR windowClassName = "DetecatAndMountMessageOnlyWindow";;
windowClass.lpszClassName = windowClassName;
if (!RegisterClass(&windowClass)) {
std::cout << "Failed to register window class" << std::endl;
return 1;
}
HWND messageWindow = CreateWindow (windowClassName, 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, 0, 0);
//HWND messageWindow = CreateWindow (windowClassName, 0, 0, 0, 0, 0, 0, (HWND) NULL, 0, 0, 0);
if (!messageWindow) {
std::cout << "Failed to create message-only window" << std::endl;
return 1;
}
static HDEVNOTIFY hDeviceNotify;
DoRegisterDeviceInterfaceToHwnd(GUID_DEVINTERFACE_VOLUME, messageWindow, &hDeviceNotify);
MSG msg;
BOOL bRet;
std::cout << "before loop" << std::endl;
while ( (bRet = GetMessage (&msg, 0, 0, 0)) != 0 )
{
std::cout << "inside loop" << std::endl;
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
std::cout << msg.wParam << std::endl;
return msg.wParam;
}
int main()
{
int result = processWindowsMessages();
return 0;
}