tags:

views:

112

answers:

1

Hi,

I am trying to learn the Windows API. Currently I am having a lot of trouble trying to get hooks to work. I have some sample code I have been messing around with for a few days - it has a GUI written in C# or something, and a dll in C++. The dll has this function externalized:

bool __declspec(dllexport) InstallHook(){
    g_hHook      = SetWindowsHookEx(WH_CBT, (HOOKPROC) CBTProc, g_hInstance, 0);
    return g_hHook != NULL;
}

CBT Proc is this, also in the dll:

LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam){
    if (nCode < 0)
        return CallNextHookEx(g_hHook, nCode, wParam, lParam);
    /* Something should go here to do stuff when certain nCodes are recieved.*/
    return 0;
}

When I run this guys code, everything works fine. He has a call to InstallHook() buried somewhere in his C# GUI, and if I put a breakpoint in the CBTProc function, I can see that it is called over and over by the system. As I don't really understand C#, I am trying to cut it out with the following (tiny) console application:

int _tmain(int argc, _TCHAR* argv[]){
    bool bbbb = InstallHook();
    Sleep(2000);
    return 0;
}

My problem is that if I do this, the hook no longer works. With the debugger I can see that InstallHook() is called correctly, and that g_hHook in that function is not null, but the CBTProc function is not called at all - its as if the system forgets about the hook as soon as it leave the InstallHook() function.

Can anyone shine light on this issue? I've been pulling my hair out for days trying to get it to work, but I have had no luck.

+1  A: 

I suspect this is because you have console application and system does not send notifications about activating, creating, moving, etc. of console windows. Try to make it normal windows application.

Paul
That worked, thanks. Its a little annoying as my program has now gone from a cool 4 lines to 100 to initialize all the windows stuff, but I am glad it works.
Oliver