Borja López
Borja López

Reputation: 2403

WebBrowser Control TextInput events

I'm struggling with the WebBrowser control (both in Winforms and WPF). Basically I want to achieve the same behavior I got with a RTF editor: Handling some kind of OnTextInput event in order to get the last typed character for every keystroke.

I mean the textual characters, not Control, Alt, F5, Enter, ... that can be captured with the Keydown/Keyup events.

Any help? Thanks in advance.

Upvotes: 1

Views: 138

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125342

You can hanlde KeyPress event of this.webBrowser1.Document.Body:

private void Form1_Load(object sender, EventArgs e)
{
    this.webBrowser1.Navigate("http://www.google.com");
    //Attach a handler to DocumentCompleted
    this.webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}


void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    //Attach a handler to Body.KeyPress when the document completed
    this.webBrowser1.Document.Body.KeyPress += Body_KeyPress;
}

void Body_KeyPress(object sender, HtmlElementEventArgs e)
{
    //handle the event, for example show a message box
    MessageBox.Show(((char)e.KeyPressedCode).ToString());
}

Note:

  • It doesn't handle non-input keys as you need.
  • You can also suppress the input by setting e.ReturnValue = false; based on some criteria if you need.
  • You can also handle other key events like KeyUp and KeyDown the same way

Upvotes: 1

Related Questions