Problems having content in webbrowser scale automatically in Windows Form Application

别来无恙 提交于 2019-12-06 09:29:58

As an option, you can handle DocumentCompleted event of the WebBrowser control and set the style of image based on the size.

For example:

1) Create a Windows Forms Project 2) Open Form1 in desgn mode and drop a WebBrowser control on it. 3) Double click on title-bar of form to handle Load event of the form and use following code:

private void Form1_Load(object sender, EventArgs e)
{
    this.webBrowser1.Navigate("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
}

4) Double click on WebBrowser control to handle its DocumentCompleed event and use following code:

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    webBrowser1.Document.Body.SetAttribute("scroll", "no");
    var img = webBrowser1.Document.GetElementsByTagName("img")
                 .Cast<HtmlElement>().FirstOrDefault();
    var w = img.ClientRectangle.Width;
    var h = img.ClientRectangle.Height;
    img.Style = string.Format("{0}: 100%", w > h ? "Width" : "Height");
}

You will see following result, while the original image size is 544x184:

Note 1

This is just an example of what you can do. You can make the decision more intelligent, for example check if the image size is less than the browser size, then you don't need to apply any scaling.

Note 2 - (This is my choice)

If you setup WebBrowser control to support showing modern content the better style for the image will be:

img.Style = "max-width:100%;max-height:100%";

This way, the image will be fit in the browser when it's larger than browser. Also it will not resize when the browser is large enough.

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