Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 694
Martin Niederl Avatar asked Dec 19 '25 22:12

Martin Niederl


1 Answers

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;
}
like image 130
Reza Aghaei Avatar answered Dec 22 '25 10:12

Reza Aghaei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!