user3752782
user3752782

Reputation: 9

SetWindowHookEx() returns NULL

I'm trying to create an application that will be notified about each active window change in Windows so it could do some tasks like detecting window titles, therefore "punishing" bad people accessing bad content on our PC machines. So, this is really important for the application because it's purpose is to log "bad" applications from history.

So, in my main function, I started a thread for my WindowLogger.

windowThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) WindowLogger,
        (LPVOID) argv[0], 0, NULL );

if (windowThread)
{
    // Also a bit of protection here.. 
    return WaitForSingleObject(windowThread, INFINITE);
}

Then, here is my WindowLogger procedure:

// Function called by main function to install hook
DWORD WINAPI
WindowLogger(LPVOID lpParameter)
{

    HHOOK hWinHook;

    HINSTANCE hExe = GetModuleHandle(NULL);

    if (!hExe)
    {
        return 1;
    }
    else
    {
        hWinHook = SetWindowsHookEx(WH_CBT, (HOOKPROC) CBTProc, hExe, 0);

        MSG msg;

        // I AM UNSURE ABOUT THIS PART.. 
        // Probably wrong code :D .. 

       while (GetMessage(&msg, NULL, 0, 0) != 0)
        {
             if (msg.message == HCBT_ACTIVATE) {
                // my code to log the window name
            }
        }
        UnhookWindowsHookEx(hWinHook);
    }
    return 0;
}

And finally, my CBTProc callback function, it logs the windows using my log() function:

LRESULT CALLBACK
CBTProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    switch (nCode)
    {

    case HCBT_ACTIVATE:
    {
        HWND foreground = GetForegroundWindow();
        char window_title[50];
        if (foreground)
            GetWindowText(foreground, window_title, 25);

            log("|");
            log(&window_title[0]);
            log("|");  

        }
    }
}

So I had debugged the program and what I figured out is that hWinHook becomes NULL after SetWindowsHookEx() -- this is what probably causes my program to mailfunction.. .. Can you help me out with this?

Thanks in advance.

Upvotes: 0

Views: 119

Answers (1)

Jonathan Potter
Jonathan Potter

Reputation: 37132

Passing 0 for the dwThreadId parameter to SetWindowsHookEx is used to register a hook for all threads in the system, i.e. a global hook. However to do this, your hook code needs to be located within a DLL (so that the DLL can be mapped into the address space of other processes). Since your hook code is in your main executable rather than a DLL the call is failing.

Upvotes: 2

Related Questions