SetWindowsHookEx ignores hooks from MS Word

I am trying to catch events when a user enters Word in my add-in, and I have the following code

delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll")]
static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll")]
static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
const int WH_KEYBOARD_LL = 13;
const int WM_KEYDOWN = 256;
static IntPtr hook;
static void Main()
{
    HookProc hp = new HookProc(HookCallback);
    hook = SetWindowsHookEx( WH_KEYBOARD_LL, hp, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0 );
    //UnhookWindowsHookEx( hook );
    //GC.KeepAlive( hp );
}
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();
        var thread = new Thread(() => { MessageBox.Show(pressedKey); });
        thread.Start();
    }
    return CallNextHookEx(hook, nCode, wParam, lParam);
}

It usually works when I type in any application except the MS Word instance that launches the add-in. Any ideas why Word is being ignored?

thank

+4
source share
1 answer

I have a similar problem, although the only solution (and a bad one) is as follows:

  • Create a separate process
  • Use shared memory or some other simple communication method to tell the DLL / VSTO running in Word.

( ) - , , , , - . , , Word .

+1

All Articles