Home > Net >  WebBrowser's ShowPrintPreviewDialog() does not show up
WebBrowser's ShowPrintPreviewDialog() does not show up

Time:11-12

I have a winforms application where I want to display print preview via System.Windows.Forms.WebBrowser control.

Here is my helper class:

using System;
using System.Windows.Forms;

namespace Hobbysta.App.Controls.Print
{
    public class PrintingContent
    {
        private readonly string htmlContent;

        public PrintingContent(string htmlContent)
        {
            this.htmlContent = htmlContent;
        }

        public void ShowPreview()
        {
            ExecuteBrowserAction(b => b.ShowPrintPreviewDialog());
        }

        private void ExecuteBrowserAction(Action<WebBrowser> action)
        {
            var browser = new WebBrowser();
            browser.DocumentCompleted  = (_, __) =>
            {
                action(browser);
                browser.Dispose();
            };
            browser.DocumentText = htmlContent;
        }
    }
}

I call it from a form with a button:

        private void button1_Click(object sender, EventArgs e)
        {
            var result = new PrintingContent("TEST PRINT");
            result.ShowPreview();
        }

As a result, new window is created, I can see it on the tab, but it cannot be brought to display by any mean. Clicking on miniature does nothing.

What am I missing here?

CodePudding user response:

It doesn't work because you've disposed it. Comment out (remove):

browser.Dispose();

private void ExecuteBrowserAction(Action<WebBrowser> action)
{
        var browser = new WebBrowser();
        browser.DocumentCompleted  = (_, __) =>
        {
            action(browser);
            //browser.Dispose();
        };

        browser.DocumentText = htmlContent;
}
  • Related