等待 WebBrowser 完成加载时出现 Application.DoEvents() 问题
我正在尝试加载 WebBrowser 内容,然后我想添加一些文本并滚动到底部。
这是我的代码示例:
webBrowser1.Url = new System.Uri("file:///" + filePath);
webBrowser1.Document.Body.InnerHtml += text;
webBrowser1.Document.Body.ScrollTop = webBrowser1.Document.Body.ScrollRectangle.Height;
当我运行它时,出现未处理的异常“对象引用未设置到对象的实例”。或者,当我对滚动的行进行注释时,文本将添加到 Web 浏览器的先前内容中,然后导航到新内容。
因此,在示例代码的第一行之后,我输入:
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents();
但它弄乱了一切。我的应用程序正在做一些非常奇怪的事情,例如多次调用同一个方法,而它应该被调用一次。
有什么解决办法吗?
I'm trying to load WebBrowser content and after that I want to add some text and scroll to the bottom.
Here's example of my code:
webBrowser1.Url = new System.Uri("file:///" + filePath);
webBrowser1.Document.Body.InnerHtml += text;
webBrowser1.Document.Body.ScrollTop = webBrowser1.Document.Body.ScrollRectangle.Height;
When I run it, there's an unhandled exception "Object reference not set to an instance of an object". Or when I comment line that does the scrolling, then text is added to previous content of the WebBrowser and then navigating to new content.
So after 1st line of my example code I put:
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents();
but it messes up everything. My application is doing really strange things, for example calling the same method many times, when it should be called once.
Is there any solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您实际上想订阅
DocumentCompleted
事件。Application.DoEvents
< /a> 仅处理挂起的 Windows 消息循环项目。无论哪种情况,请确保您了解可能的缺点 在使用它之前调用
DoEvents
。I think you actually want to subscribe to
DocumentCompleted
event.Application.DoEvents
only processes pending Windows message loop items.In either case, make sure you understand possible drawbacks of calling
DoEvents
before using it at all.DoEvents()
在这里是一个糟糕的解决方案。您应该使用显式线程或 BackgroundWorker 来加载页面并让 UI 线程处理其他内容。DoEvents()
is a bad solution here. You should use explicit thread orBackgroundWorker
to load pages and leave UI thread to handle other stuff.