Web 浏览器控件滚动到工作,但随后恢复为 0



所以我试图通过使用 Web 浏览器控件在更改 HTML 时呈现它来向用户展示他们键入的一些 HTML 的预览。 这工作正常,除了浏览器在每次更改后滚动到顶部。所以我把它放进去:

private void txtTemplateText_TextChanged(object sender, EventArgs e)
{
int top = 0;
if (this.webBrowser.Document != null) top = this.webBrowser.Document.Body.ScrollTop;
this.webBrowser.DocumentText = this.txtTemplateText.Text;
if (this.webBrowser.Document != null) this.webBrowser.Document.Window.ScrollTo(0, top);
}

在他们输入 HTML 的文本框的文本更改事件中。如果我逐步完成此代码,则一切正常。这些价值观是我所期望的。当我执行 ScrollTo 行时,一切看起来都很好,但是当我 F10 关闭右大括号时,浏览器控件的滚动位置将返回到 0,即使在该行之后没有执行其他代码。

如果我将值硬编码为 1000(而不是变量 top(,我实际上可以看到滚动位置被正确设置,然后它回到 0。

我无法想象是什么在重置此值并导致滚动位置在正确后发生变化。

我不敢相信这奏效了。 我不得不把这一行放在ScrollTo行之前:

Application.DoEvents(); // must have this so document has been loaded before trying to set scroll, otherwise it goes to top

我假设文档实际上没有加载(即使在单步执行时(,因此此时设置 scroll 属性不起作用,因为没有什么可以滚动到的,即使看起来有。

最新更新