我創建不使用以下方法http://pietschsoft.com/post/2008/07/C-Generate-WebPage-Thumbmail-Screenshot-Image.aspx如何在工作線程上創建和使用WebBrowser控件?
我試圖使應用程序的多線程網站截屏的應用程序,但我遇到了以下錯誤:
[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()函數實現從上面的網址複製:
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;
}
我有點困惑,你試圖在非GUI線程內創建和操作瀏覽器控件。你有沒有可能將繁重的工作與控制權的交互分離開來,將繁重的工作委託給工作者線程? – Tormod 2010-01-03 18:02:03
以及我試圖做到這一點,但我卡住了。 – Karim 2010-01-03 18:19:01