gpt4 book ai didi

c# - 我如何在工作线程上创建和使用 WebBrowser 控件?

转载 作者:行者123 更新时间:2023-11-30 13:42:47 25 4
gpt4 key购买 nike

我正在创建一个使用以下方法截取网站屏幕截图的应用程序 http://pietschsoft.com/post/2008/07/C-Generate-WebPage-Thumbmail-Screenshot-Image.aspx

我试图使应用程序成为多线程,但我遇到了以下错误:

[ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment.]

有什么解决这个问题的建议吗?我的代码基本上如下:

List<string> lststrWebSites = new List<string>();
lststrWebSites.Add("http://stackoverflow.com");
lststrWebSites.Add("http://www.cnn.com");
foreach (string strWebSite in lststrWebSites)
{
System.Threading.ThreadStart objThreadStart = delegate
{
Bitmap bmpScreen = GenerateScreenshot(strWebSite, -1, -1);
bmpScreen.Save(@"C:\" + strWebSite + ".png",
System.Drawing.Imaging.ImageFormat.Png);
};
new System.Threading.Thread(objThreadStart).Start();
}

GenerateScreenShot() 函数的实现是从上面的 URL 复制过来的:

public Bitmap GenerateScreenshot(string url)
{
// This method gets a screenshot of the webpage
// rendered at its full size (height and width)
return GenerateScreenshot(url, -1, -1);
}

public Bitmap GenerateScreenshot(string url, int width, int height)
{
// Load the webpage into a WebBrowser control
WebBrowser wb = new WebBrowser();
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(url);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{ Application.DoEvents(); }


// Set the size of the WebBrowser control
wb.Width = width;
wb.Height = height;

if (width == -1)
{
// Take Screenshot of the web pages full width
wb.Width = wb.Document.Body.ScrollRectangle.Width;
}

if (height == -1)
{
// Take Screenshot of the web pages full height
wb.Height = wb.Document.Body.ScrollRectangle.Height;
}

// Get a Bitmap representation of the webpage as it's rendered in
// the WebBrowser control
Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
wb.Dispose();

return bitmap;
}

最佳答案

与许多 ActiveX 控件一样,WebBrowser 具有严格的线程要求。创建它的线程必须使用 Thread.SetApartmentState() 进行初始化以将其切换到 STA。并且线程必须泵出一个消息循环,您可以从 Application.Run() 获得一个消息循环。

这使得与浏览器的对话变得非常棘手。这是让您入门的代码。请注意,已完成回调在后台线程上运行。不要忘记调用 Dispose() 来关闭线程。

using System;
using System.Threading;
using System.ComponentModel;
using System.Windows.Forms;

class WebPagePump : IDisposable {
public delegate void CompletedCallback(WebBrowser wb);
private ManualResetEvent mStart;
private SyncHelper mSyncProvider;
public event CompletedCallback Completed;

public WebPagePump() {
// Start the thread, wait for it to initialize
mStart = new ManualResetEvent(false);
Thread t = new Thread(startPump);
t.SetApartmentState(ApartmentState.STA);
t.IsBackground = true;
t.Start();
mStart.WaitOne();
}
public void Dispose() {
// Shutdown message loop and thread
mSyncProvider.Terminate();
}
public void Navigate(Uri url) {
// Start navigating to a URL
mSyncProvider.Navigate(url);
}
void mSyncProvider_Completed(WebBrowser wb) {
// Navigation completed, raise event
CompletedCallback handler = Completed;
if (handler != null) handler(wb);
}
private void startPump() {
// Start the message loop
mSyncProvider = new SyncHelper(mStart);
mSyncProvider.Completed += mSyncProvider_Completed;
Application.Run(mSyncProvider);
}
class SyncHelper : Form {
WebBrowser mBrowser = new WebBrowser();
ManualResetEvent mStart;
public event CompletedCallback Completed;
public SyncHelper(ManualResetEvent start) {
mBrowser.DocumentCompleted += mBrowser_DocumentCompleted;
mStart = start;
}
public void Navigate(Uri url) {
// Start navigating
this.BeginInvoke(new Action(() => mBrowser.Navigate(url)));
}
void mBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
// Generated completed event
Completed(mBrowser);
}
public void Terminate() {
// Shutdown form and message loop
this.Invoke(new Action(() => this.Close()));
}
protected override void SetVisibleCore(bool value) {
if (!IsHandleCreated) {
// First-time init, create handle and wait for message pump to run
this.CreateHandle();
this.BeginInvoke(new Action(() => mStart.Set()));
}
// Keep form hidden
value = false;
base.SetVisibleCore(value);
}
}
}

关于c# - 我如何在工作线程上创建和使用 WebBrowser 控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1995527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com