在新线程中创建Webbrowser并将其绘制在表单上
本文关键字:绘制 表单 Webbrowser 创建 新线程 线程 | 更新日期: 2023-09-27 18:30:07
我正在使用此代码在新线程中创建一个web浏览器控件
void Exec(string url)
{
var th = new Thread(() =>
{
using (WebBrowser wb = new WebBrowser())
{
wb.DocumentCompleted += (sndr, e) =>
{
// Do something when completed
wb.Dispose();
Application.ExitThread();
};
wb.Navigate(url);
Application.Run();
}
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
}
现在,每次调用此方法时,它都会创建web浏览器控件的新实例。我的问题是,当创建新实例时,是否可以在窗体上绘制/重新绘制控件?
试试这个。不过可能会进行优化。
void Exec(string url)
{
var th = new Thread(() =>
{
using (WebBrowser wb = new WebBrowser())
{
wb.Name = "webBrowserGenerated" + Guid.NewGuid();
List<Control> list = new List<Control>();
GetAllControl(this, list);
foreach (Control control in list)
{
if (control.GetType() == typeof(WebBrowser))
{
if (control.Name.StartsWith("webBrowserGenerated"))
{
control.Refresh();
}
}
}
wb.DocumentCompleted += (sndr, e) =>
{
// Do something when completed
wb.Dispose();
Application.ExitThread();
};
wb.Navigate(url);
Application.Run();
}
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
}
private void GetAllControl(Control c, List<Control> list)
{
foreach (Control control in c.Controls)
{
list.Add(control);
if (control.GetType() == typeof(Panel))
GetAllControl(control, list);
}
}