在Dialog程序中使用WH_KEYBOARD_LL类型HOOK

类别:VC语言 点击:0 评论:0 推荐:

在Dialog程序中使用WH_KEYBOARD_LL类型HOOK的方法:

SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)LowLevelKeyboardProc, AfxGetApp()->m_hInstance, NULL);

LRESULT CALLBACK LowLevelKeyboardProc (INT nCode, WPARAM wParam, LPARAM lParam)
{
    // By returning a non-zero value from the hook procedure, the
    // message does not get passed to the target window

    KBDLLHOOKSTRUCT *pkbhs = (KBDLLHOOKSTRUCT *) lParam;
    BOOL bControlKeyDown = 0;

    switch (nCode)
    {
        case HC_ACTION:
        {
            // Check to see if the CTRL key is pressed
            bControlKeyDown = GetAsyncKeyState (VK_CONTROL) >> ((sizeof(SHORT) * 8) - 1);
           
            // Disable CTRL+ESC
            if (pkbhs->vkCode == VK_ESCAPE && bControlKeyDown)
                return 1;

            // Disable ALT+TAB
            if (pkbhs->vkCode == VK_TAB && pkbhs->flags & LLKHF_ALTDOWN)
                return 1;

            // Disable ALT+ESC
            if (pkbhs->vkCode == VK_ESCAPE && pkbhs->flags & LLKHF_ALTDOWN)
                return 1;

            // Response to Up
            if ((pkbhs->vkCode == VK_UP) && (WM_KEYUP == wParam))
            {
                    HWND hwnd=::FindWindow(NULL, "WindowCaption");
                    ::PostMessage(hwnd, WM_COMMAND, ID_MENU_ITEM, 0L);
            }
        }
        default:
            break;
    }
    return CallNextHookEx (NULL, nCode, wParam, lParam);
}

BOOL InstallKbHook( )
 {

    if (hhookKb )
        UninstallKbHook();

    hhookKb = SetWindowsHookEx(WH_KEYBOARD_LL,
        (HOOKPROC)LowLevelKeyboardProc, AfxGetApp()->m_hInstance, NULL);

    return(hhookKb != NULL);

}

BOOL UninstallKbHook()
{

    BOOL fOk = FALSE;
    if (hhookKb ) {
        fOk = UnhookWindowsHookEx(hhookKb );
        hhookKb = NULL;
    }

    return(fOk);
}

本文地址:http://com.8s8s.com/it/it365.htm