如何获得“按键”?事件来自Word 2010插件(c#开发)
本文关键字:插件 2010 Word 开发 何获得 按键 事件 | 更新日期: 2023-09-27 18:14:22
如何从c#开发的Word 2010插件中"捕获"KeyPress事件?
注意:我不是在寻找"复杂"的解决方案,比如挂钩的东西,而是为了美观和整洁. net甚至从对象模型。
我"in my hands"的应用对象是:
Microsoft.Office.Interop.Word.Application
不幸的是,在Word API或VSTO中没有任何内置的可以拾取击键,更多信息可以在这里找到
我一直在寻找一个可行的解决方案一段时间,但我能想到的最好的是通过Windows API使用钩子来处理它,很可能你会得到同样的结论,所以这里有一个例子:
你需要在以下程序集中添加一个using
指令:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
这里是钩子:
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);
}
}
您可以尝试使用Excel WebBrowser控件而不是System.Windows.Forms WebBrowser;它处理特殊的键转发如TAB, DEL, CTRL+V等
将WebBrowser的构造函数从
更改new System.Windows.Forms.WebBrowser();
new Microsoft.Office.Tools.Excel.Controls.WebBrowser();
你需要添加引用到你的项目:项目/添加引用/扩展选择Microsoft.Tools.Outlook &Microsoft.Tools.Outlook.v4.0.Utilities