Reputation: 9555
How do you use a webbrowser control in code behind of a asp.net page. I get this error:
ActiveX control cannot be instantiated because the current thread is not in a single-threaded apartment.
thanks for the help
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
Upvotes: 1
Views: 2059
Reputation: 4209
This is working:
/// <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();
}
}
}
Upvotes: 0
Reputation: 13965
Why do you want to use WebBrowser behind the scenes in a ASP.NET app? If you need to interact with a web page on another server, usually people do that using HttpWebRequest
.
Somebody out there can correct me if I'm wrong, but I believe a web app, almost by definition, cannot be single-threaded. Web apps are meant to be multi-user, to be doing multiple things and accommodating multiple users at once.
Upvotes: 1