C ++ Console application, SetWindowsHookEx, Callback never called

I have a small console application with a built-in v8 engine, and I would like to add a hook for registering key events. All this worked before I used Qt and QtScript, but I port it all directly to C ++ in VC ++ 2008. The application compiles and runs, but the hook is never called, here is the corresponding code:

In main ()

HWND hwndC = GetConsoleWindow() ; HINSTANCE hInst = (HINSTANCE)GetWindowLong( hwndC, GWL_HINSTANCE ); if (SetWindowsHookEx(WH_KEYBOARD_LL, HookProc, hInst, NULL) == 0) { printf("Failed to set hook\n"); } else { printf("Hook established\n"); } g->RunScript(argc,argv); 

And proc:

 LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam) { printf("HookProc called\n"); PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT) (lParam); if (wParam == WM_KEYDOWN) { keyDown(p,g); } else if (wParam == WM_KEYUP) { keyUp(p,g); } fflush(stdout); return CallNextHookEx(NULL, nCode, wParam, lParam); } 

This is essentially an extension to shell.cc from the v8 example code. Interestingly, does this somehow block? I admit that I do not know what I'm doing here, I just play and study, but I have a dead end.

Inside keyDown I will say that I have something like this:

  v8::Handle<v8::String> callback_name = v8::String::New("onKeyDown"); v8::Handle<v8::Value> callback_val = g->_context->Global()->Get(callback_name); if (!callback_val->IsFunction()) { printf("No onKeyDown handler found\n"); return; } v8::Handle<v8::Function> callback = v8::Handle<v8::Function>::Cast(callback_val); const int argc = 1; v8::Handle<v8::Value> argv[argc] = { v8::Int32::New(char(p->vkCode)) }; printf("Calling onKeyDown\n"); v8::Handle<v8::Value> result = callback->Call(g->_context->Global(), argc, argv); 

In the end, some of them may not work, but it is never called when the program starts and defines: onKeyDown = function (key) {...}; I see that onKeyDown works very well, I can use all my related C ++ method, etc. From JS, so this thing is just driving me crazy.

Any help, perhaps pointers to some training materials, would be greatly appreciated.

Just to be clear, this function in c: LRESULT CALLBACK HookProc (int nCode, WPARAM wParam, LPARAM lParam) is never called or never sees printf, and the output at the beginning says: β€œThe hook is installed, so the window says that the hook is set .

/ Jason

+4
source share
2 answers

A low level hook, such as WH_KEYBOARD_LL, requires your application to loop through messages. This is the only way that Windows can infiltrate your thread and make the HookProc callback you registered.

An application in console mode does not pump the message loop, as regular Windows GUI applications do. Judging by your fragment, adding it is also not easy. You will need to create a stream.

+7
source

Maybe this feature will help you? GetAsyncKeyState

0
source

All Articles