如何在asp.net页后面的代码中使用webbrowser控件。我得到了这个错误:
无法实例化ActiveX控件,因为当前线程不在单线程单元中。
谢谢你的帮助
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Web.UI.WebControls
Partial Class _Default
Dim testcontrol As New WebBrowser() ' it breaks here
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
testcontrol.Navigate("mysite")
End Sub
End Class发布于 2013-02-15 22:28:52
为什么要在ASP.NET应用程序的幕后使用WebBrowser?如果你需要与另一台服务器上的网页进行交互,人们通常会使用HttpWebRequest。
如果我错了,有人可以纠正我,但我相信,几乎根据定义,web应用程序不能是单线程的。Web应用程序应该是多用户的,要做多件事,一次可以容纳多个用户。
发布于 2013-03-01 16:31:07
这是有效的:
/// <summary>
/// Returns a thumbnail for the current member values
/// </summary>
/// <returns>Thumbnail bitmap</returns>
protected Bitmap GetThumbnail()
{
try
{
// WebBrowser is an ActiveX control that must be run in a single-threaded
// apartment so create a thread to create the control and generate the
// thumbnail
Thread thread = new Thread(new ThreadStart(GetThumbnailWorker));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return _bmp;
}
catch (Exception ex)
{
using (StreamWriter writer = new StreamWriter("log.txt", true))
{
writer.WriteLine(string.Format("[{0}] {1}", DateTime.Now.ToString(), ex.ToString()));
writer.Flush();
writer.Close();
}
return null;
}
}
/// <summary>
/// Creates a WebBrowser control to generate the thumbnail image
/// Must be called from a single-threaded apartment
/// </summary>
protected void GetThumbnailWorker()
{
try
{
using (WebBrowser browser = new WebBrowser())
{
browser.ClientSize = new Size(_width, _height);
//browser.ScrollBarsEnabled = false;
browser.ScriptErrorsSuppressed = true;
browser.Navigate(_url);
// Wait for control to load page
while (browser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
// Render browser content to bitmap
_bmp = new Bitmap(_thumbWidth, _thumbHeight);
browser.DrawToBitmap(_bmp, new Rectangle(0, 0, _thumbWidth, _thumbHeight));
}
}
catch (Exception ex)
{
using (StreamWriter writer = new StreamWriter("log.txt", true))
{
writer.WriteLine(string.Format("[{0}] {1}", DateTime.Now.ToString(), ex.ToString()));
writer.Flush();
writer.Close();
}
}
}https://stackoverflow.com/questions/14895771
复制相似问题