6
votes

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.

1
Selection change is for a change of state when "highlighting text". (msdn.microsoft.com/en-us/library/…), look for something like "KeyUp", "KeyDown" or "KeyPress", although a quick search didn't yield anything.Phil Price
@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 inputyohannist

1 Answers

5
votes

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.