2010-09-02 37 views

回答

6

對,這可能不會起作用。 WebBrowser控件旨在被單個STA線程使用。它不會很好地映射到Web服務中的MTA,並且可能需要一些主要的駭客。

你想做什麼?如果你能描述你的問題,我們可能會想出一個替代解決方案。


編輯

好吧,這可能是可能的,雖然肯定哈克。這裏有一個理論實現:

  1. 分離一個STA線程,讓Web服務線程等待它。
  2. 在STA線程中加載瀏覽器。
  3. 導航到所需的網頁。導航完成時,請截取屏幕截圖。
  4. 將屏幕截圖發送回Web服務線程。

的代碼會是這個樣子:

public Bitmap GiveMeScreenshot() 
{ 
    var waiter = new ManualResetEvent(); 
    Bitmap screenshot = null; 

    // Spin up an STA thread to do the web browser work: 
    var staThread = new Thread(() => 
    { 
     var browser = new WebBrowser(); 
     browser.DocumentCompleted += (sender, e) => 
     { 
      screenshot = TakeScreenshotOfLoadedWebpage(browser); 
      waiter.Set(); // Signal the web service thread we're done. 
     } 
     browser.Navigate("http://www.google.com"); 
    }; 
    staThread.SetApartmentState(ApartmentState.STA); 
    staThread.Start(); 

    var timeout = TimeSpan.FromSeconds(30); 
    waiter.WaitOne(timeout); // Wait for the STA thread to finish. 
    return screenshot; 
}; 

private Bitmap TakeScreenshotOfLoadedWebpage(WebBrowser browser) 
{ 
    // TakeScreenshot() doesn't exist. But you can do this using the DrawToDC method: 
    // http://msdn.microsoft.com/en-us/library/aa752273(VS.85).aspx 
    return browser.TakeScreenshot(); 
} 

而且,從過去的經驗記:我們已經看到在System.Windows.Forms.WebBrowser不瀏覽,除非它的加入問題到視覺父母,例如表單。你的旅費可能會改變。祝你好運!

+0

我想要做的是讓WCF服務呈現一個html頁面並抓取一個快照並將其保存到磁盤。謝謝。 – 2010-09-02 02:19:08

+0

好的。這是可能的,只是可能會讓屁股工作變得有點痛苦。我正在更新我的答案以包含理論實現。 – 2010-09-07 14:11:30

+0

我已經更新了我的答案,包括一個可能的解決方案,儘管它是駭人聽聞的。 – 2010-09-07 14:28:47

相關問題