views:

162

answers:

3

I have added a keyboard hook for a dialog that I don't control (it runs its own DialogProc Function in a library with closed source). I'm able to capture the key strokes, but the key stroke is always sent the dialog. This causes error beeps as well as some weird behavior.

Installing the hook:

hKeyHook=SetWindowsHookEx(WH_KEYBOARD, KeyHookProc, hInst, GetCurrentThreadId());

The hook function:

LRESULT CALLBACK KeyHookProc(int code, WPARAM wParam, LPARAM lParam)
{
    if(!(lParam & 0x80000000))
    {
        if(wParam == VK_mykey)
        {
            // Do my stuff

            return 0;  // Don't continue the hook chain
        }
    }

    // Continue with next hook
    return CallNextHookEx(hKeyHook, code, wParam, lParam);
}

Releasing the hook:

UnhookWindowsHookEx(hKeyHook);

Is there a way to stop the key stroke from being sent to the control that has focus in the dialog?

+3  A: 

You could subclass the control in question by replacing its GWLP_WNDPROC (See the remarks section of this page) value. The basic concept is that you filter out the WM_KEY* messages, then pass the rest to the original WndProc.

Ben Straub
A: 

This

if(!(lParam & 0x80000000))

is true when the key is pressed. When it's released you do nothing.

KeyHookProc is called when the keys are held down or when they are released.

Nick D
A: 

Hmm. First point are you sure that you wish to use your own process thread id here. Is the dialog definitely under your process thread?

ChrisBD
In this case it is actually my thread, but I agree it isn't clear from the question.
Peter Olsson