Martin Niederl
Martin Niederl

Reputation: 759

Trigger event when WebBrowser text selection changed

Two parts of my program are a winforms WebBrowser and a simple TextBox.

What I want now is, when I select a text in the WebBrowser it automatically copies the selected text in the TextBox.

I could not find anything about this on google so I'd be glad if someone could help me!

Upvotes: 3

Views: 1906

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125342

You can attach an event handler to onselectionchange event of Document of the WebBrowser control using AttachEventHandler method of document. Then you can use properties of DomDocument to get selected text.

Example

void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
{
    webBrowser1.Document.AttachEventHandler("onselectionchange", selectionchange);
}
private void selectionchange(object sender, EventArgs e) 
{
    dynamic document = webBrowser1.Document.DomDocument;
    dynamic selection = document.selection;
    dynamic text = selection.createRange().text;
    this.textBox1.Text= (string)text;
}

Upvotes: 4

Willy David Jr
Willy David Jr

Reputation: 9171

You can try this, but this need a trigger example a button click for the value to be passed on your TextBox1. Unfortunately, mouse event is not supported on WebBrowser control.

 dynamic document = webBrowser1.Document.DomDocument;
 dynamic selection = document.selection;
 dynamic text = selection.createRange().text;
 TextBox1.Text = text;

Upvotes: 0

Related Questions