Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF WebBrowser - How to Zoom Content?

Trying to test basic browser concepts in a WPF (C#/XAML, .NET 4.0) WebBrowser application. So far, the only problem is programatically zooming. Has anyone had any experience with this?

MSDN lists nothing: http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.aspx Additionally, I have tried various things such as RenderTransform options to no avail. Either this is not possible or not documented. I'm hoping for the latter. Note that a WinForm solution isn't acceptable.

Thanks in advance for any help, Beems

like image 952
Beems Avatar asked Feb 25 '11 20:02

Beems


2 Answers

Maybe you can execute a javascript like this.

document.body.style.zoom = 1.5;

In WPF we can manipulate the document. I Created a Extension Method for you, so you can set the Zoom:

// www.tonysistemas.com.br
public static partial class MyExtensions
{
    public static void SetZoom(this System.Windows.Controls.WebBrowser WebBrowser1, double Zoom)
    {
        // For this code to work: add the Microsoft.mshtml .NET reference      
        mshtml.IHTMLDocument2 doc = WebBrowser1.Document as mshtml.IHTMLDocument2;
        doc.parentWindow.execScript("document.body.style.zoom=" + Zoom.ToString().Replace(",", ".") + ";");
    }
}

Usage:

WebBrowser1.SetZoom(0.5);
like image 144
Tony Avatar answered Oct 16 '22 16:10

Tony


I used bits and pieces from this answer https://stackoverflow.com/a/7326179/17822 to assist with the zoom issue. The key here is the ExecWB method. The zoom on the Windows Desktop is not 1-1 to the zoom on the WebBrowser Control. You will have to play with it. The pseudo-code for the equation looks like this:

zoomLevel = (winDesktopZoom - 100) + _winDesktopZoom + 10

Note that you will need a reference to SHDocVw.dll which can be found in the C:\Windows\SysWOW64 for x64 machines and in C:\Windows\System32 for x86 machines.

This is not pretty, but it is the only thing that I have found, short of upgrading to http://awesomium.com that actually matches IE default zoom settings (which default to the Windows Desktop zoom) to WebBrowser Control. Also note that the Windows Desktop Zoom only exists for Vista, Win 7 and probably 2k8 as well in the Control Panel --> Display, but I didn't check Vista or 2k8. It is not there for XP (any service pack).

To get the Windows Desktop Zoom (this does work on XP for some reason) I did:

var presentSource = PresentationSource.FromVisual(this);

if (presentSource != null && presentSource.CompositionTarget != null 
    && presentSource.CompositionTarget.TransformToDevice != null)
{
    _zoomPercentage = Convert.ToInt32(100 * presentSource.CompositionTarget.TransformToDevice.M11);
}

This logic is placed in the OnSourceInitialized override for that XAML Window.

like image 20
Daniel McQuiston Avatar answered Oct 16 '22 15:10

Daniel McQuiston