VSTO应用程序中加入键盘钩子
在VSTO应用程序中有时为了处理一些快捷按键操作等实现一些特殊的功能,此时需要对键盘进行挂钩,此时使用P/Invoke函数实现,参考如下:
VSTO加载和卸载时进行钩子的初始化和卸载
代码
KeyboardHook hook;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
hook = new KeyboardHook();
hook.InitHook();
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
hook.UnHook();
}
}
//钩子具体处理逻辑是:
class KeyboardHook
{
#region (invokestuff)
[DllImport("kernel32.dll")]
static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx(int code, HookProcKeyboard func, IntPtr hInstance, uint threadID);
[DllImport("user32.dll")]
static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll")]
static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
#endregion
#region constans
private const int WH_KEYBOARD = 2;
private const int HC_ACTION = 0;
#endregion
delegate int HookProcKeyboard(int code, IntPtr wParam, IntPtr lParam);
private HookProcKeyboard KeyboardProcDelegate = null;
private IntPtr khook;
bool doing = false;
public void InitHook()
{
uint id = GetCurrentThreadId();
//init the keyboard hook with the thread id of the Visual Studio IDE
this.KeyboardProcDelegate = new HookProcKeyboard(this.KeyboardProc);
khook = SetWindowsHookEx(WH_KEYBOARD, this.KeyboardProcDelegate, IntPtr.Zero, id);
}
public void UnHook()
{
if (khook != IntPtr.Zero)
{
UnhookWindowsHookEx(khook);
}
}
private int KeyboardProc(int code, IntPtr wParam, IntPtr lParam)
{
try
{
if (code != HC_ACTION)
{
return CallNextHookEx(khook, code, wParam, lParam);
}
if ((int)wParam == (int)Keys.Z && ((int)lParam & (int)Keys.Alt) != 0)
{
if (!doing)
{
doing = true;
MessageBox.Show("Captured");
doing = false;
}
}
}
catch
{
}
return CallNextHookEx(khook, code, wParam, lParam);
}
}