Zoom WPF-WebBrowser-Control Content

天大地大妈咪最大 提交于 2019-12-25 07:50:50

问题


I´d like to show a website inside the wpf WebBrowser Control. But the content size is to large, so that there are scrollbars as you can see here:

I would like to display the whole site in this window, without resizing it. I´d like to zoom inside the page so that it looks like this:

I´d like to prevent doing it with JavaScript. The WPF way shown here WPF WebBrowser - How to Zoom Content? also didn´t work for me. It always says the mshtml.IHTMLDocument2 is null.

I also like to prevent doing it with WindowsForms. I hope there is a "only XAML" - way to solve this problem.

This is my code:

<Window x:Class="BrowserApp.MainWindow"

 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <WebBrowser Source="https://www.google.de/"></WebBrowser>
        </Grid>
    </Window>

Thank you!

EDIT

This is my code inside the Webbrowser1_Navigated-Method, where the HRESULT: 0x80020101-Error occurs.

private void Webbrowser1_Navigated(object sender, NavigationEventArgs e)
{
    double Zoom = 0.5;
    mshtml.IHTMLDocument2 doc = Webbrowser1.Document as mshtml.IHTMLDocument2;
    doc.parentWindow.execScript("document.body.style.zoom=" + Zoom.ToString().Replace(",", ".") + ";");
}

回答1:


It always says the mshtml.IHTMLDocument2 is null.

This has to do with the threading model of the web browser control. Any navigation you have setup either in XAML or in code will not complete until after you leave your constructor. This means you have to do your zoom code either after the Navigated event fires or after a timer fires.

This is how I would do it.

            public MainWindow()
            {
                InitializeComponent();
                Webbrowser1.Navigate("http://www.google.com"); //won't complete until you leave this code block
                Webbrowser1.Navigated += Webbrowser1_Navigated;

            }

            private void Webbrowser1_Navigated(object sender, NavigationEventArgs e)
            {
               //do your zoom code here
            }
}

In your XAML you could reference the event, but you would still have to do the zoom part.

   <WebBrowser Navigated="Webbrowser1_Navigated" Name="Webbrowser1"/>

Certainly the other stackoverflow post's code is fine for zooming.




回答2:


webBrowser.LoadCompleted += Web_LoadCompleted;

private void Web_LoadCompleted (object sender, NavigationEventArgs e)
{
    // Place your code here
}


来源:https://stackoverflow.com/questions/41871274/zoom-wpf-webbrowser-control-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!