在Windows服务中使用WebBrowser或WebKit.Net对象

时间:2011-05-24 03:01:38

标签: c# vb.net windows-services

嘿伙计们,我正在尝试创建一个Windows服务来加载网站,导航它,并使用javascript提取一些信息。这在Windows窗体应用程序中非常容易实现,但是不能在Web服务中工作(显然是因为服务无法访问注册表WinInet Not Supported for Use in Services)。任何想法如何让它工作?这是我的代码,什么都不输出:

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 information to the file.
            fileStream.Write(info, 0, info.Length);
        }
        finally
        {
            fileStream.Close();
        }
    }
编辑:我需要一个WebBrowser或WebKit.Net对象,因为我需要在页面上执行javascript,我需要维护一个登录(使用cookie和发布数据)。如果有另一种方法可以做到这一点,请告诉我。

1 个答案:

答案 0 :(得分:2)

您需要在表单中托管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
}