How do I setup a system wide hook to listen for WM_DEVICECHANGE?

  • Thread starter Thread starter NabeelOmer
  • Start date Start date
N

NabeelOmer

Guest
I want to setup a System wide hook to listen for WM_DEVICECHANGE in C++. I know that hooks are setup using SetWindowsHookEx(). I have done this before for Keyboard messages (WM_KEYUP, WM_KEYDOWN) but I want to do it for WM_DEVICECHANGE. I am currently using:

#include <windows.h>
#include <tchar.h>
#include <iostream>
void WinHook();
LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam);

int _tmain(int argc, _TCHAR* argv[])
{

WinHook();
std::cout << GetLastError() << " winhook\n";
return 0;
}


void WinHook()
{

HHOOK hook = NULL;
hook = SetWindowsHookEx(WH_GETMESSAGE, HookProc, NULL, GetCurrentThreadId());
std::cout << GetLastError() << " sethook\n";
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam){
std::cout << GetLastError() << " hookproc called\n";
switch (wParam){
case WM_DEVICECHANGE: std::cout << "SUCCESS!!!!!"; break;
default: return CallNextHookEx(NULL, nCode, wParam, lParam);
}
}


Edit: The GetLasterror() after SetWindowsHookEx() returns 0, and the one in the function HookProc() is never called.

Continue reading...
 
Back
Top