Using a WebBrowser or WebKit.Net object in a Windows Service
Hey guys, I'm trying to create a windows service that loads a website, navigates it, and pulls some information using javascript. This is all very easy to do in a windows forms application, but isn't working in a webservice (apparently because services can't access the registry WinInet Not Supported for Use in Services). Any ideas how to get it to work? Here's my code that outputs nothing:
volatile WebBrowser webBrowser2;
protected override void OnStart(string[] args)
{
ThreadStart threadDelegate = new ThreadStart(myThread);
Thread thread = new Thread(threadDelegate);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
public void myThread()
{
webBrowser2 = new WebBrowser();
webBrowser2.Navigate("http://www.google.com");
webBrowser2.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHand开发者_JAVA技巧ler(this.webpage_loaded2);
Thread.Sleep(60000);
FileStream fileStream = new FileStream(@"c:\file1.txt", FileMode.Create);
try
{
Byte[] info = new UTF8Encoding(true).GetBytes("services app output: " + webBrowser2.DocumentText);
// Add some information to the file.
fileStream.Write(info, 0, info.Length);
}
finally
{
fileStream.Close();
}
}
EDIT: I need a WebBrowser or WebKit.Net object because I need to execute javascript on the page, and I need to maintain a login (using cookies and post data). If there's another method to do this please let me know.
You need to host your WebBrowser control in a Form and then inside your windows service start your form. WebBrowser can't do anything without a form.
protected override void OnStart(string[] args)
{
ThreadStart threadDelegate = new ThreadStart(myThread);
Thread thread = new Thread(threadDelegate);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
//let the form start with some sleep time or whatever you want
ActionsToExecuteInWebBrowser();
}
void myThread()
{
Application.Run(new FormHostingWebBrowserControl());
}
void ActionsToExecuteInWebBrowser()
{
//Whatever you want to do in the WebBrowser here
}
精彩评论