从.net(C#)中的Webbrowser控件中检索所选文本

Cli*_*iff 16 c# webbrowser-control winforms

我一直在试图弄清楚如何在我的webbrowser控件中检索用户选择的文本,并且在通过msdn和其他资源挖掘后没有运气,所以我想知道是否有办法实际执行此操作.也许我只是错过了什么.

我感谢任何关于此的帮助或资源.

谢谢

Ash*_*Ash 44

您需要使用WebBrowser控件的Document.DomDocument属性并将其强制转换为Microsoft.mshtml互操作程序集中提供的IHtmlDocument2接口.这使您可以访问在IE中实际运行的Javascript可用的完整DOM.

为此,首先需要将项目的引用添加到Microsoft.mshtml程序集中,通常位于"C:\ Program Files\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll".可能有多个,请确保选择此路径的引用.

然后获取当前文本选择,例如:

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

有关从.NET应用程序访问完整DOM的更多信息,请参阅:

  • @Ash,如果我使用WPF的webBrowser怎么办?WPF的webBrowser没有webBrowser1.Document.DomDocument (4认同)

use*_*ame 5

以防万一有人对不需要添加对 mshtml.dll 的引用的解决方案感兴趣:

private string GetSelectedText()
{
    dynamic document = webBrowser.Document.DomDocument;
    dynamic selection = document.selection;
    dynamic text = selection.createRange().text;
    return (string)text;
}
Run Code Online (Sandbox Code Playgroud)