Keyboard hook fires multiple times in MS Word
Asked Answered
F

1

1

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.

Favourite answered 1/9, 2016 at 6:40 Comment(0)
F
0

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.

Favourite answered 22/9, 2016 at 8:57 Comment(1)
I am experiencing the same issue with the hookcall back being executed multiple times. How did you solve this?Newbill

© 2022 - 2024 — McMap. All rights reserved.