简体   繁体   English

在WCF服务中使用System.Windows.Forms.WebBrowser控件需要做什么?

[英]What do I need to do to use the System.Windows.Forms.WebBrowser control in a WCF service?

I believe the WebBrowser control is STA and a WCFservice hosted in a NT Service is MTA ? 我相信WebBrowser控件是STA,NT服务中托管的WCF服务是MTA吗? Thanks. 谢谢。

Right, this likely will not work. 对,这可能行不通。 The WebBrowser control was meant to be used by a single STA thread. WebBrowser控件旨在由单个STA线程使用。 It won't map well to MTA in a web service, and will likely require some major hackery. 它不会很好地映射到Web服务中的MTA,并且可能需要一些主要的hackery。

What are you trying to do? 你想做什么? If you can describe your problem, we may be able to come up with an alternative solution. 如果您能描述您的问题,我们可能会提出替代解决方案。


edit 编辑

Ok, this is probably possible, although certainly hacky. 好吧,这可能是可能的,虽然肯定是hacky。 Here's a theoretical implementation: 这是一个理论实现:

  1. Spin up an STA thread, have the web service thread wait for it. 启动STA线程,让Web服务线程等待它。
  2. Load the browser in the STA thread. 在STA线程中加载浏览器。
  3. Navigate to the desired web page. 导航到所需的网页。 When navigation finishes, take the screenshot. 导航完成后,请截取屏幕截图。
  4. Send the screenshot back to web service thread. 将屏幕截图发送回Web服务线程。

The code would look something like this: 代码看起来像这样:

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

Also, a note from past experience: we've seen issues where the System.Windows.Forms.WebBrowser doesn't navigate unless it's added to a visual parent, eg a Form. 此外,来自过去经验的一个注释:我们已经看到System.Windows.Forms.WebBrowser不会导航的问题,除非它被添加到可视父级,例如Form。 Your mileage may vary. 你的旅费可能会改变。 Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM