Unable to use WebBrowser.DocumentCompleted event in a Windows Service.

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi,<br/><br/>I am using WebBrowser class instance to print HTML reports. My code works fine in a Windows Application but I am unable to use the same functionality in a Windows Service. It gives an error saying that the control can only run in a thread which is in a Single Threaded Apartment. <br/><br/>I tried the following code to make it work:<br/><br/>
<div style="background-color:white;color:black
<pre> <span style="color:blue private <span style="color:blue static AutoResetEvent av = <span style="color:blue new AutoResetEvent(<span style="color:blue false);<br/>
<span style="color:blue private <span style="color:blue static <span style="color:blue void PrintReport()
{
<span style="color:blue try
{
Thread newThread = <span style="color:blue new Thread(<span style="color:blue new ThreadStart(CreateBrowser1));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
av.WaitOne(-1, <span style="color:blue false);
}
<span style="color:blue catch (Exception ex)
{
EventLog.WriteEntry(<span style="color:#a31515 "PrintReport", <span style="color:#a31515 "Error Occurred: " + ex.Message);
}
}

<span style="color:blue private <span style="color:blue static <span style="color:blue void CreateBrowser()
{
<span style="color:blue try
{
<span style="color:blue string URL = <span style="color:#a31515 "http://www.google.com";
WebBrowser webBrowser1 = <span style="color:blue new WebBrowser();
webBrowser1.Url = <span style="color:blue new Uri(URL);
<span style="color:blue while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
System.Threading.Thread.Sleep(50);
}
webBrowser1.Print();
<span style="color:blue int count = 100;
<span style="color:blue while (count-- > 0)
{
Application.DoEvents();
Thread.Sleep(100);
}
webBrowser1.Dispose();
}
<span style="color:blue catch (Exception ex)
{
EventLog.WriteEntry(<span style="color:#a31515 "CreateBrowser", <span style="color:#a31515 "Error Occurred: " + ex.Message);
}
<span style="color:blue finally
{
av.Set();
}



[/code]

<br/><br/>I want to make use of DocumentCompleted event instead of ReadyState property. This is because ReadyState property is not working properly. Please tell me how to go about it.<br/><br/>Thanks in advance,<br/>Sumit

View the full article
 
Back
Top