6

I am developing a MS-Word addon in which my code has to get access to the letters the user is entering through the keyboard.

private void ThisDocument_Startup(object sender, System.EventArgs e)
{
    this.SelectionChange += new SelectionEventHandler(ThisDocument_SelectionChange);
}

void ThisDocument_SelectionChange(object sender, SelectionEventArgs e)
{
    MessageBox.Show(e.Selection.Text);
}

I think the SelectionChange event can give me the text but the event is not raised at keypress, Is there any way to trigger the event at keypress? Also if there is a more straightforward way to do it or an open source project that give the functionality, it would be welcome.

Mohammad Arshad Alam
  • 9,694
  • 6
  • 38
  • 61
yohannist
  • 4,166
  • 3
  • 35
  • 58
  • 1
    Selection change is for a change of state when "highlighting text". (http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.selectionchange(v=vs.80).aspx), look for something like "KeyUp", "KeyDown" or "KeyPress", although a quick search didn't yield anything. – Phil Price Oct 24 '12 at 16:16
  • 1
    See http://stackoverflow.com/questions/13000645/capturing-keydown-event-of-ms-word-using-c-sharp – Phil Price Oct 24 '12 at 16:18
  • @PhilPrice, The answer suggests that there is no direct "KeyUp" or "KeyDown" event that can be accessed from visual studio. I'm using the "SelectionChange" event as a work-around. If i can trigger it i can capture the character at the cursor. BTW it can already be triggered by the arrow keys. Anyway thanks for the input – yohannist Oct 24 '12 at 16:25

1 Answers1

5

Microsoft doesn't expose a key down event natively, but there's a workaround.

I implemented keyboard checking with help from the article linked below:

http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state

This gives you a static method called IsKeyDown, implementing and invoking a delegate you can subscribe to should be fairly straight forward.

Soeholm
  • 1,102
  • 14
  • 15
  • +1 Thank you for this answer. I am thinking of using this approach. Is the code you have implemented reliable? I mean, does Office/Word get in the way, and intermittently stop it from working? Thank you. – Sabuncu Sep 06 '13 at 18:41
  • I'm not sure, I didn't use it for a word addon :) – Soeholm Sep 12 '13 at 14:05
  • @Soeholm The link you provided is now dead. – Jared Oct 12 '15 at 02:49
  • Here's a copy of the dead link: https://web.archive.org/web/20121102085806/http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state – Sabuncu Mar 17 '16 at 11:54
  • How do you mean it "implementing and invoking a delegate". Could you add this to your answer. – ninjaxelite Jul 01 '19 at 13:49