Word Addin本地键盘挂钩

时间:2015-10-31 13:04:44

标签: c# windows keyboard-hook

我正在尝试创建一个具有自动更正功能的MS Word插件。下面的代码块取自here。但它会捕获任何应用程序中的所有关键事件。我知道这是正常的,因为在这一行:

SetWindowsHookEx(WH_KEYBOARD_LL, procedure, GetModuleHandle(module.ModuleName), 0);

最后一个参数是线程id,当它等于0时,这意味着一个全局钩子。但是,当我尝试将其更改为:

SetWindowsHookEx(WH_KEYBOARD_LL, procedure, GetModuleHandle(module.ModuleName), AppDomain.GetCurrentThreadId());

它什么都没有。我还尝试了来自

AppDomain.GetCurrentThreadId()process.Threads[0].Id,而不是GetCurrentThreadId()

[DllImport("Kernel32.Dll")] public static extern uint GetCurrentThreadId();

它们都返回相同的id,除0之外的任何值都不起作用。我该怎么办?

public partial class ThisAddIn
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;

    private static IntPtr hookId = IntPtr.Zero;
    private delegate IntPtr HookProcedure(int nCode, IntPtr wParam, IntPtr lParam);
    private static HookProcedure procedure = HookCallback;

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook, HookProcedure lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);  

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        hookId = SetHook(procedure);
    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
        UnhookWindowsHookEx(hookId);
    }

    private static IntPtr SetHook(HookProcedure procedure)
    {
        using (Process process = Process.GetCurrentProcess())
        using (ProcessModule module = process.MainModule)
            return SetWindowsHookEx(WH_KEYBOARD_LL, procedure, GetModuleHandle(module.ModuleName), 0);
    }

    private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int pointerCode = Marshal.ReadInt32(lParam);
            string pressedKey = ((Keys)pointerCode).ToString();

            //Do some sort of processing on key press
            var thread = new Thread(() => { MessageBox.Show(pressedKey); });
            thread.Start();
        }
        return CallNextHookEx(hookId, nCode, wParam, lParam);
    }

    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }
}

0 个答案:

没有答案