c# - Outlook功能区控件上的Keyboardhook

时间:2012-11-29 07:46:38

标签: c# setwindowshookex

我想挂钩一个特定的控件(一个组合框)并接收在该控件中键入的所有键。 Combobox是Outlook功能区的一部分,没有像按键或其他东西的事件(只是onChange,表现得非常奇怪)。

以下是代码:

    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private LowLevelKeyboardProc _proc;
    private IntPtr _hookID = IntPtr.Zero;

    private void SetHook(IntPtr handle)
    {
        uint PID; //not needed
        _proc = HookCallback;
        uint threadid = GetWindowThreadProcessId(handle, out PID);
        _hookID = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, IntPtr.Zero, threadid );

    }

    private delegate IntPtr LowLevelKeyboardProc(
            int nCode, IntPtr wParam, IntPtr lParam);

    private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            System.Diagnostics.Debug.WriteLine("Key: " + (Keys)vkCode);
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

我拥有的句柄和我获得的ThreadID是正确的(通过Spy ++验证)但没有捕获密钥。工作正常,“0”作为SetWindowsHookEx函数的最后一个参数,但随后是一个全局的钩子。

1 个答案:

答案 0 :(得分:1)

我为有相同问题的人添加此内容。 Keyboardhooks是全局的,无法挂钩到特定的控件。您需要做的是捕获给定句柄的消息。为此,您必须继承窗口/句柄。

    [DllImport("user32")]
    private static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, Win32WndProc newProc);
    [DllImport("user32")]
    private static extern int CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, int Msg, int wParam, int lParam);

    // A delegate that matches Win32 WNDPROC:
    private delegate int Win32WndProc(IntPtr hWnd, int Msg, int wParam, int lParam);

    // from winuser.h:
    private const int GWL_WNDPROC = -4;
    private const int WM_KEYDOWN = 0x0100;

    // program variables
    private IntPtr oldWndProc = IntPtr.Zero;
    private Win32WndProc newWndProc = null;

    private void SubclassHWnd(IntPtr hWnd)
    {
        // hWnd is the window you want to subclass..., create a new 
        // delegate for the new wndproc
        newWndProc = new Win32WndProc(MyWndProc);
        // subclass
        oldWndProc = SetWindowLong(hWnd, GWL_WNDPROC, newWndProc);
    }

    private const int ENTER_KEY = 1835009;

    // this is the new wndproc, just show a messagebox on left button down:
    private int MyWndProc(IntPtr hWnd, int Msg, int wParam, int lParam)
    {

        switch (Msg)
        {
            case WM_KEYDOWN:
                int vkCode = lParam;
                if (vkCode == ENTER_KEY)
                    doSomething();
                return 0;

            default:
                break;
        }

        return CallWindowProc(oldWndProc, hWnd, Msg, wParam, lParam);
    }