Attempting CBT Hook

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Why doesnt this work?<br/><br/>"SetWindowsHookEx" seems to work (at least I receive a non-zero value).  But CBTProc never gets called (DebugView never shows anything).  "UnhookWindowsHookEx" returns zero - which indicates that it failed.  And "GetLastError" returns 1404 - "Invalid hook handle".<br/><br/>If you try the code, be sure to turn off pre-compiled headers.<br/><br/><br/>
<div style="background-color:white;color:black
<pre>#include <tchar.h>
#include <conio.h>
#include <windows.h>

HHOOK hCBTHook = NULL;
HINSTANCE hInstance = NULL;
<span style="color:blue int iCBTCtr = 0;

LRESULT CALLBACK CBTProc(<span style="color:blue int, WPARAM, LPARAM);

<span style="color:blue int _tmain(<span style="color:blue int argc, _TCHAR* argv[]) {
hInstance = GetModuleHandle(NULL);
hCBTHook = SetWindowsHookEx(WH_CBT, CBTProc, hInstance, 0);

_cputs(<span style="color:#a31515 "Press any key to end . . .");
_getch();

BOOL b = UnhookWindowsHookEx(hCBTHook);
DWORD dwErr = GetLastError();

<span style="color:blue return 0;
}

LRESULT CALLBACK CBTProc(<span style="color:blue int nCode, WPARAM wParam, LPARAM lParam) {
TCHAR pcBuffer[2048];
swprintf_s(pcBuffer, _countof(pcBuffer), L<span style="color:#a31515 "++CBT++ %Ii", ++iCBTCtr);
OutputDebugString(pcBuffer);
<span style="color:blue return CallNextHookEx(hCBTHook, nCode, wParam, lParam);
}
[/code]
<br/>Before anyone writes asking what Im trying to accomplish.  Im trying to write the following:<br/>*   A C++ console app that establishes a CBT hook.<br/>*   The CBT hook will count the number of CBT messages generated and display this in DebugView.<br/>*   When the user presses any key the hook is released and the app ends.<br/>

View the full article
 
Back
Top