1

我想挂钩特定控件(组合框)并接收在该控件中键入的所有键。组合框是 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 函数的最后一个参数可以正常工作,但它当然是一个全局挂钩。

4

1 回答 1

1

我为任何有同样问题的人添加这个。键盘挂钩是全局的,不能挂钩到特定控件。您需要做的是捕获给定句柄的消息。为此,您必须对窗口/句柄进行子类化。

    [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);
    }
于 2012-11-30T07:29:47.140 回答