1

I'm trying to create a MS Word addin with an auto-correct feature. The code block below is taken from here. However it catches all the key events from any application. I know this is normal because in this line:

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

the last parameter is the thread id and when it is equal to 0 which means a global hook. But when I try to change it to:

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

It catches nothing. Instead of AppDomain.GetCurrentThreadId(), I also tried process.Threads[0].Id or GetCurrentThreadId() from

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

They all return the same id and any value other than 0 not works. What do I do?

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);
    }
}
Community
  • 1
  • 1
hrzafer
  • 1,123
  • 1
  • 15
  • 35
  • The `..._LL` hooks are always global. – Raymond Chen Oct 31 '15 at 18:57
  • @Raymond Is there a way to at least detect the source application of the key event and skip in the HookCallback method? – hrzafer Oct 31 '15 at 19:23
  • Low-level hooks are called before the system even decides which application is going to get the key. Maybe you want to use a standard hook. – Raymond Chen Nov 01 '15 at 01:36
  • By standard hook do you mean `WH_KEYBOARD`? I did so and it indeed catches only the current thread's events. But the condition `wParam==(IntPtr)WM_KEYDOWN` returns false in this case. And I couldn't find any sample code using `WH_KEYBOARD` where there are plenty using `WH_KEYBOARD_LL`. – hrzafer Nov 01 '15 at 14:15
  • The documentation for `WH_KEYBOARD` says that it uses a `KeyboardProc`, and the [documentation for `KeyboardProc`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms644984(v=vs.85).aspx) explains what the parameters are. I don't know why people love `WH_KEYBOARD_LL` so much. – Raymond Chen Nov 01 '15 at 15:25

0 Answers0