I am trying to catch events when user is typing in 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);
}
generally it works when I type in any application except in the instance of MS Word which runs the add-in. Any ideas why is the Word ignored?
Thanks