3

I have a form with webbrowser control ,where i am coping all the TEXT(not html) data to clipboard

For this the code snippet is :-

webBrowser2.Document.ExecCommand("SelectAll", false, null);
webBrowser2.Document.ExecCommand("Copy", false, null);

I have written the above code under webBrowser2_DocumentCompleted .

The problem is that the webpage in webbrowserControl appears with selection. I want to clear that selection after copy operation.

Is there a way to do this or a command such as

 webBrowser2.Document.ExecCommand("ClearSelection", false, null);  //This doesn't work
anurag
  • 137
  • 2
  • 11

3 Answers3

4

If you import the Microsoft.mshtml library (C:\Program Files\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll), you can use the selection property of the web-browser's Document:

using mshtml;

...

IHTMLDocument2 htmlDocument = webBrowser2.Document.DomDocument as IHTMLDocument2;

IHTMLSelectionObject selection = htmlDocument.selection;

if (selection != null) {
    selection.clear();
}

Otherwise, you could always Navigate to a script URI:

webBrowser2.Navigate("javascript:document.selection&&document.selection.clear();");

Edit: Changed it to use Navigate, instead of InvokeScript.

Toothbrush
  • 2,080
  • 24
  • 33
  • second method is not working on my machine and web browser goes blank. – anurag Jan 22 '14 at 12:52
  • no it did not. The web browser only loads master page content and rest everything is blank – anurag Jan 23 '14 at 07:11
  • 4
    htmlDocument.execCommand("UNSELECT", false, Type.Missing); worked for me. I found this on http://www.ssicom.org/js/x277333.htm . – anurag Jan 23 '14 at 07:42
2

If you want to unselect the selection then use:

htmlDocument.ExecCommand("Unselect", false, Type.Missing);

But if you want to remove (hide) a word selected:

IHTMLDocument2 htmlDocument = webBrowser2.Document.DomDocument as IHTMLDocument2;
IHTMLSelectionObject selection = htmlDocument.selection;

if (selection != null) {
    selection.clear();
}
greene
  • 637
  • 6
  • 6
1

I was able to use the Refresh method of the browser control to do the same thing. (i.e. webBrowser2.Refresh())

Thomas Sapp
  • 917
  • 8
  • 10