键盘挂钩在MS Word中触发多次 [英] Keyboard hook fires multiple times in MS Word

查看:105
本文介绍了键盘挂钩在MS Word中触发多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是参考虽然Dirk Vollmar提供的答案有效,但我注意到按一个键会触发KeyboardHookCallBack 10-12次,并且我无法准确捕获按击键的顺序.

While the answer provided by Dirk Vollmar works, I noticed that hitting one key triggers KeyboardHookCallBack 10-12 times and I am not able to capture accurately the sequence the keys are being hit in.

请问我,如果我的问题很愚蠢,但是有没有办法确保每个键只触发一次KeyboardHookCallBack?我已经尝试了一段时间了,没有任何运气.

Pardon me if my question is stupid but is there a way to make sure that the KeyboardHookCallBack is triggered only once for each key? I have been trying this for some time now without any luck.

在此问题上的帮助将不胜感激.

I'd appreciate any help on this matter.

推荐答案

我的要求是在MS Word中实现具有智能感知功能的自动完成功能.我已经决定,每次用户按下空格键时,我都应该尝试跟踪用户自上次按下空格键以来所按下的键.基于检测文本更改的解决方案在VSTO加载项的Word 2016中,我没有按正确的顺序按下键,并且钩子回调执行了多次.尽管我发现了解决问题的肮脏方法,但是解决方案并不是完全可靠的.花了几天的时间后,我想出了一种解决方法,我觉得这应该可以解决.在这里:

My requirement was to implement auto-complete feature with intellisense in MS Word. I had decided that every time user hits a space bar I should try to track what keys the user had pressed since he last hit the space bar. Based on the solution at Detecting text changes in Word 2016 from VSTO add-in I wasn't getting the keys pressed in a proper sequence and the hook callback executed multiple times. Although I had found a dirty way to get around the problem, the solution wasn't full-proof. After spending a few days I have come up with a workaround and I feel this one should work. Here it goes:

private IntPtr KeyboardHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
    string key = ((System.Windows.Forms.Keys)wParam).ToString‌();
    if (key == "Space")
    {
        Word.Selection sel = Globals.ThisAddIn.Application.Selection;
        Word.Range rng = sel.Range.Paragraphs[1].Range;
        object unitWord = Word.WdUnits.wdWord;
        object countN1 = -1;
        sel.MoveStart(ref unitWord, ref countN1);
        string userInput = sel.Words[1].Text;
        sel.MoveRight(ref unitWord, ref missing, ref missing);
    }
}

希望这可以帮助所有在类似问题上挣扎的人们.

Hope this helps all the people struggling with similar issue.

这篇关于键盘挂钩在MS Word中触发多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆