【问题标题】:how to get selected text in webbrowser control如何在 webbrowser 控件中获取选定的文本
【发布时间】:2013-09-07 22:02:41
【问题描述】:

我可以通过以下方式在 WPF 中获取网络浏览器控件的选定文本:

IHTMLDocument2 doc1 = webBrowser.Document as IHTMLDocument2;
        IHTMLDocument3 doc = webBrowser.Document as IHTMLDocument3;

        IHTMLSelectionObject currentSelection = doc1.selection;

        if (doc1.selection.type == "Text")
        {
            IHTMLTxtRange range = (IHTMLTxtRange)doc1.selection.createRange();
        }

这很好用,如果我将 range.text 的值设置为其他值,它会更改文本的值。我遇到的唯一问题是在 Gmail 等带有某种所见即所得编辑器的网页上,selection.type 始终为“无”。我怀疑这是因为文本编辑器在技术上是一个子文档。我不确定如何查找子文档并检查是否选择了文本。谁能帮我?谢谢!

【问题讨论】:

    标签: c# wpf webbrowser-control


    【解决方案1】:

    您可以检查document.activeElement 是否是一个框架并具有contentWindow 属性(document.activeElement.contentWindow != null)然后您可以使用contentWindow.document 来获取框架的内部document。递归执行此操作,直到找到带有document.selection != null 的帧。

    为了说明这一点:

    main.html:

    <!DOCTYPE html>
    <body>
    <iframe src="iframe.html"></iframe>
    </body>
    

    iframe.html

    <!DOCTYPE html>
    <head>
    <script>
    window.onload = function()
    {
        window.focus();
        document.execCommand("SelectAll", false);
    }
    </script>
    </head>
    <body contentEditable="true">
    This is editable
    </body>
    

    C#:

    var text = this.wb.Document.InvokeScript("eval", new object[] {
        "document.activeElement.contentWindow.document.selection.createRange().text" });
    MessageBox.Show(text.ToString());
    

    演出:

    这是可编辑的

    【讨论】:

      猜你喜欢
      • 2011-03-24
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 2014-10-09
      • 2023-03-12
      • 2012-04-13
      相关资源
      最近更新 更多