MFC全键盘钩

时间:2013-06-10 20:11:53

标签: c++ user-interface mfc keyboard hook

当应用程序不在焦点时,应用程序如何检测凯按? [解决了] 我需要在插入按键时启动计时器,并在应用程序窗口未聚焦时再次按下。 任何人都可以向我展示源代码或基于MFC的示例吗? 我知道MFC没有那种类型的成员,但是如何在MFC中实现正确的源代码? 如何按键启动计时器?

  // MainHamsterDlg.cpp : implementation file

        #include "stdafx.h"
        #include "MainHamsterDlg.h"

        // MainHamsterDlg dialog
        IMPLEMENT_DYNAMIC(MainHamsterDlg, CDialogEx)

        MainHamsterDlg::MainHamsterDlg(CWnd* pParent)
            : CDialogEx(MainHamsterDlg::IDD, pParent)
        {

        }

        void MainHamsterDlg::DoDataExchange(CDataExchange* pDX)
        {
            CDialogEx::DoDataExchange(pDX);
        }


        BEGIN_MESSAGE_MAP(MainHamsterDlg, CDialogEx)
            ON_WM_TIMER()
        END_MESSAGE_MAP()


        HHOOK _hook;
        KBDLLHOOKSTRUCT kbdStruct;

        LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam)
        {
            if (nCode >= 0)
            {
                // the action is valid: HC_ACTION.
                if (wParam == WM_KEYUP)
                {
                    kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
                    // a key (non-system) is pressed.
                    if (kbdStruct.vkCode == VK_INSERT)
                    {
                       SetTimer(NULL, 0, 0, NULL); <<<----- this don't starts timer 
                    }
                }
            }
           return CallNextHookEx(_hook, nCode, wParam, lParam);
        }

        void SetHook()
        {
            if (!(_hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0)))
            {
                MessageBox(NULL, "Failed to install hook!", "Error", MB_ICONERROR);
            }
        }

        void ReleaseHook()
        {
            UnhookWindowsHookEx(_hook);
        }

        BOOL MainHamsterDlg::OnInitDialog()
        { SetHook();

            //SetTimer(0, 0, NULL); <<<------- this starts timer 
            CDialogEx::OnInitDialog();

            return TRUE;
        }

        void MainHamsterDlg::OnTimer(UINT nIDEvent)
        {
        //do something
              CDialog::OnTimer(nIDEvent);
        }

1 个答案:

答案 0 :(得分:1)

您可以使用SetWindowsHookEx

这允许您为任何回调创建全局挂钩。