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

I believe the WebBrowser control is an STA, and the WCF service hosted in the NT service is an MTA? Thank.

+3
source share
1 answer

That's right, this is unlikely to work. The WebBrowser control was intended to be used by a single STA thread. It will not display well in the MTA in the web service and will most likely require a serious hacker.

What are you trying to do? If you can describe your problem, we can offer an alternative solution.


change

Well, maybe it's possible, although of course it's hacked. Here's a theoretical implementation:

  • STA, , - .
  • STA.
  • -. .
  • -.

:

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 , , . . . !

+6

Source: https://habr.com/ru/post/1762769/


All Articles