1

If I scale a WebBrowser control (e.g. with a Viewbox) its content doesn't scale along with it. Here's a sample:

<Viewbox>
    <StackPanel Background="LightBlue">
        <Label Content="XAML xaml"/>
        <WebBrowser Source="C:\MyPath\Test.html" />
    </StackPanel>
</Viewbox>

HTML showing the same font size regardless of how big its WebBrowser control is

I have a WPF application that loads and displays hundreds of local HTML files. However, the HTML appears very tiny on a 3840x2160 display because my Viewbox is unable to stretch the HTML content the way it stretches everything else. I have however noticed that I can zoom WebBrowser content with touch gestures or the mouse wheel.

What's the best way to solve this problem? I can think of several avenues to explore.

  1. Get WebBrowser content to scale with the control somehow.
  2. Programmatically zoom the WebBrowser document to match the Viewbox scaling.
  3. Find another way to display HTML content in WPF.
  4. Convert the HTML to XAML.

Microsoft made a suggestion that seems to be related to this issue and I tried implementing it as described in this answer on another question: https://stackoverflow.com/a/40657760/2122672

But that doesn't really make sense to me. It seems to have more to do with disabling the context menu than scaling the HTML.

Kyle Delaney
  • 11,616
  • 6
  • 39
  • 66

1 Answers1

0

I used an extension method that zooms and then makes sure the scrollbar is at the top. It requires some unusual references: Microsoft Internet Controls for the zooming and Microsoft.mshtml for the scrolling.

public static void SetZoom(this System.Windows.Controls.WebBrowser wb, int zoom)
{
    try
    {
        FieldInfo webBrowserInfo = wb.GetType().GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);

        object comWebBrowser = null;
        object zoomPercent = zoom;

        if (webBrowserInfo != null)
            comWebBrowser = webBrowserInfo.GetValue(wb);
        if (comWebBrowser != null)
        {
            InternetExplorer ie = (InternetExplorer)comWebBrowser;
            ie.ExecWB(OLECMDID.OLECMDID_OPTICAL_ZOOM, OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, ref zoomPercent, IntPtr.Zero);

            if (wb.Document is mshtml.HTMLDocument htmlDoc)
            {
                htmlDoc.parentWindow.scrollTo(0, 0);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}
Kyle Delaney
  • 11,616
  • 6
  • 39
  • 66