gpt4 book ai didi

c# - 如何从 Word 2010 插件(用 C# 开发)获取 "KeyPress"事件?

转载 作者:可可西里 更新时间:2023-11-01 07:55:51 26 4
gpt4 key购买 nike

如何从使用 C# 开发的 Word 2010 插件“捕获”KeyPress 事件?

注意:我不是在寻找诸如 Hook 之类的“复杂”解决方案,而是为了美观整洁.NET 甚至来自对象模型。

我“掌握”的应用对象是:

Microsoft.Office.Interop.Word.Application

最好的问候

最佳答案

不幸的是,Word API 或 VSTO 中没有任何内置的东西可以获取击键,可以找到更多关于这方面的信息 here

一段时间以来,我一直在寻找可行的解决方案,但我能想到的最好办法是使用 Hook 通过 Windows API 处理它,您很可能会得出相同的结论,所以这里有一个例子:

您需要将 using 指令添加到以下程序集:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

这里是钩子(Hook):

   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);
}
}

关于c# - 如何从 Word 2010 插件(用 C# 开发)获取 "KeyPress"事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8120199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com