Friday, October 4, 2013

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

Hi,



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.



I tried the following code to make it work:





private static AutoResetEvent av = new AutoResetEvent(false);
private static void PrintReport()
{
try
{
Thread newThread = new Thread(new ThreadStart(CreateBrowser1));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
av.WaitOne(-1, false);
}
catch (Exception ex)
{
EventLog.WriteEntry("PrintReport", "Error Occurred: " + ex.Message);
}
}

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








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.



Thanks in advance,

Sumit

No comments:

Post a Comment