Keyboard hook fires multiple times in MS Word

让人想犯罪 __ 提交于 2020-01-05 04:28:16

问题


This is in reference to a question asked in Detecting text changes in Word 2016 from VSTO add-in

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.

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.


回答1:


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.



来源:https://stackoverflow.com/questions/39264317/keyboard-hook-fires-multiple-times-in-ms-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!