Retrieving Selected Text from Webbrowser control in .net(C#)

泪湿孤枕 提交于 2019-11-27 13:16:10

You need to use the Document.DomDocument property of the WebBrowser control and cast this to the IHtmlDocument2 interface provided in the Microsoft.mshtml interop assembly. This gives you access to the full DOM as is available to Javascript actually running in IE.

To do this you first need to add a reference to your project to the Microsoft.mshtml assembly normally at "C:\Program Files\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll". There may be more than one, make sure you choose the reference with this path.

Then to get the current text selection, for example:

using mshtml;

...

    IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2;

    IHTMLSelectionObject currentSelection= htmlDocument.selection;

    if (currentSelection!=null) 
    {
        IHTMLTxtRange range= currentSelection.createRange() as IHTMLTxtRange;

        if (range != null)
        {
            MessageBox.Show(range.text);
        }
    }

For more information on accessing the full DOM from a .NET application, see:

Just in case anybody is interested in solution that doesn't require adding a reference to mshtml.dll:

private string GetSelectedText()
{
    dynamic document = webBrowser.Document.DomDocument;
    dynamic selection = document.selection;
    dynamic text = selection.createRange().text;
    return (string)text;
}

And if You just use the technique bellow?

//Copy selected text to clipboard

        Clipboard.Clear();
        SendKeys.SendWait("^(c)");

//Get selected text from clipboard

        string strClip = Clipboard.GetText().Trim();
        Clipboard.Clear();

I'm assuming you have a WinForms application which includes a control that opens a website.

Check to see if you can inject/run JavaScript inside your webbrowser control. Using JavaScript, you would be able to find out what was selected and return it. Otherwise, I doubt the web browser control has any knowledge of what is selected inside it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!