2011-05-24 59 views
0

嗨,大家好,我正在嘗試創建一個加載網站,瀏覽網頁並使用javascript抽取一些信息的Windows服務。這在Windows窗體應用程序中很容易實現,但不能在web服務中工作(顯然,因爲服務無法訪問註冊表WinInet Not Supported for Use in Services)。任何想法如何讓它工作?這裏是我的代碼輸出什麼:在Windows服務中使用WebBrowser或WebKit.Net對象

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(); 
     } 
    } 

編輯:我需要一個web瀏覽器或WebKit.Net對象,因爲我需要在網頁上執行JavaScript和我需要保持登錄(使用cookie和後數據)。如果還有其他方法可以做到這一點,請告訴我。

+0

您是否設法解決此問題? – 2015-03-17 20:17:28

回答

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 
} 
+0

這看起來非常有趣,你認爲你可以在這方面進行擴展嗎?我可以將窗體添加到Windows服務項目嗎?以及如何從服務中訪問表單? – Rob 2011-05-24 04:41:36

+0

我不太清楚,我想我創建了一個單獨的Windows Form項目來創建表單,而不是通過我自己生成初始化代碼的混亂;然後將這些文件移到我的Windows服務項目並更改命名空間。 之後,我在Windows服務項目中擁有了Visual Studio Windows窗體的所有設計器優點。希望這可以幫助。 – 2011-05-24 11:54:48