C# 有没有办法动态创建和处理 Webbrowser 控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/937135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to dynamically create and dispose of Webbrowser control?
提问by Proximo
I have this App that uses the Webbrowser control to do automated browsing. I need to come up with a way to automatically close the browser (dispose), then create another instance that actually works.
我有这个应用程序,它使用 Webbrowser 控件进行自动浏览。我需要想出一种方法来自动关闭浏览器(处置),然后创建另一个实际工作的实例。
Here's some of the code that I have so far.
这是我到目前为止的一些代码。
this.webBrowser2 = new System.Windows.Forms.WebBrowser();
this.webBrowser2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.webBrowser2.Location = new System.Drawing.Point(0, 34);
this.webBrowser2.MinimumSize = new System.Drawing.Size(20, 20);
this.webBrowser2.Name = "webBrowser2";
this.webBrowser2.ScriptErrorsSuppressed = true;
this.webBrowser2.Size = new System.Drawing.Size(616, 447);
this.webBrowser2.TabIndex = 1;
So I was thinking if I dispose of the webbrower instance.
所以我在考虑是否处理 webbrower 实例。
webBrowser2.dispose();
And then creating a new instance of the webbrowser object.
然后创建 webbrowser 对象的新实例。
WebBrowser w = new WebBroswer();
w.Navigate(url);
Unfortunately this doesn't work. The new instance of the browser doesn't show up and the disposed browser object just stays frozen in the windows form.
不幸的是,这不起作用。浏览器的新实例不会出现,并且已处理的浏览器对象只是在 windows 窗体中保持冻结状态。
Is there something I am doing wrong?
有什么我做错了吗?
Thanks
谢谢
采纳答案by Matt Brindley
You need to add and remove the WebBrowsers from the form's Controls property:
您需要从表单的 Controls 属性中添加和删除 WebBrowsers:
this.Controls.Remove(webBrowser2);
this.Controls.Add(w);
If you get stuck, there's also this articlethat has an almostcomplete walkthrough to adding and removing controls (it doesn't include much about events).
如果您遇到困难,还有这篇文章,其中包含几乎完整的添加和删除控件的演练(它不包含太多关于事件的内容)。