WebBrowser.Document.Body总是空WebBrowser、Document、Body

2023-09-04 02:36:59 作者:烟花柳巷红尘客i

我有一个 web浏览器文件设置为编辑模式。我试图用 WebBrowser.Document.Body.InnerText 操纵body元素的内部文本,但 WebBrowser.Document.Body 仍然空。

I have a WebBrowser document set to be in edit mode. I am trying to manipulate the inner text of the body element by using WebBrowser.Document.Body.InnerText, however, WebBrowser.Document.Body remains null.

下面是code其中创建该文件的内容:

Here is the code where I create the document contents:

private WebBrowser HtmlEditor = new WebBrowser();
public HtmlEditControl()
{
    InitializeComponent();
    HtmlEditor.DocumentText = "<html><body></body></html>";
    myDoc = (IHTMLDocument2)HtmlEditor.Document.DomDocument;
    myDoc.designMode = "On";
    HtmlEditor.Refresh(WebBrowserRefreshOption.Completely);
    myContentsChanged = false;
}

我可以编辑code,一切都很好,但我不明白为什么 HtmlEditor.Document.Body 仍然空。我知道我可以永远只是重置文档正文每当我需要加载文本的形式,但我会preFER理解为什么是这样表现的方式是,如果不出意外,然后为知识。

I can edit code and everything fine, but I don't understand why HtmlEditor.Document.Body remains null. I know I could always just reset the document body whenever I need to load text into the form, but I would prefer to understand why this is behaving the way it is, if nothing else then for the knowledge.

任何帮助是极大的AP preciated。

Any help on this is greatly appreciated.

推荐答案

您必须等待Web浏览器的DocumentCompleted事件,火灾的DomDocument.Body不为空。我只是测试这个验证。我想,这个问题依然存在:你如何能够通过底层COM接口进行编辑时,该文件还没有完全加载?

You have to wait for the Web Browser's DocumentCompleted event to fire for the DomDocument.Body to not be null. I just tested this to verify. I suppose the question still remains: how are you able to edit through the underlying COM interface when the document has not completely loaded?

我检查,看看是否的IHTMLDocument2指针是在DocumentCompleted和构造相同。它们是,这可能表明基础COM对象重用单个HTML文档对象。好像你在构造函数中所做的任何更改,至少有覆盖掉了或抛出异常的pretty的好机会。

I checked to see if the IHTMLDocument2 pointers were the same in DocumentCompleted and the constructor. They are, which might indicate that the underlying COM object reuses a single HTML document object. It seems like any changes you make in the constructor at least have a pretty good chance of getting overwritten or throwing an exception.

例如,如果我这样做,在构造函数中,我得到一个错误:

For example, if I do this in the constructor, I get an error:

的IHTMLDocument2 P1 =(的IHTMLDocument2)HTMLEditor.Document.DomDocument;

IHTMLDocument2 p1 = (IHTMLDocument2) HTMLEditor.Document.DomDocument;

p1.title =世界,你好!;

p1.title = "Hello world!";

如果我做同样的DocumentCompleted处理程序,它工作正常。

If I do the same in a DocumentCompleted handler, it works fine.

希望这有助于。谢谢你。

Hope this helps. Thanks.