问题描述
|
大家好,我正在尝试创建一个Windows服务,该服务可以加载网站,进行导航并使用javascript提取一些信息。在Windows窗体应用程序中,这都是非常容易做到的,但是在Web服务中却不起作用(显然是因为服务无法访问注册表,但WinInet不支持在服务中使用)。有任何想法如何使其正常工作吗?这是我的代码,什么也不输出:
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.WebbrowserDocumentCompletedEventHandler(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 @R_134_4045@ion to the file.
fileStream.Write(info,info.Length);
}
finally
{
fileStream.Close();
}
}
编辑:我需要一个Webbrowser或WebKit.Net对象,因为我需要在页面上执行javascript,并且需要维护登录名(使用cookie和发布数据)。如果有另一种方法可以进行此操作,请告诉我。
解决方法
您需要在表单中托管WebBrowser控件,然后在Windows服务内部启动表单。 WebBrowser没有表单就无法做任何事情。
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
}