c# - Web 浏览器中的内容在 Windows 窗体应用程序中自动缩放时出现问题

标签 c# .net winforms webbrowser-control scale

我正在尝试创建一个程序,该程序可以滚动浏览计算机上的文件并显示这些文件。到目前为止,这对我有用,但我得到的是实际大小的内容,因此网络浏览器添加了一个滚动条(显然)。我希望内容自动缩放,以便它适合网络浏览器,而无需滚动。

代码:

 WebBrowser web = new WebBrowser();     
 System.Drawing.Rectangle workingRectangle = Screen.PrimaryScreen.WorkingArea;
 int heightWebcontrol = workingRectangle.Height / 100 * 85;
 int widthwebControl = workingRectangle.Width / 100 * 75;
 web.Size = new Size(widthwebControl, heightWebcontrol);
 web.Location = new Point(0, 0);
 web.Navigate(fileName);
 this.Controls.Add(web);

网络浏览器中的大图像,这只是图像的 1/5:

Large image

所以基本上,这个大图像需要自动缩放,以便它完全适合浏览器。

谢谢大家。

最佳答案

作为一个选项,您可以处理 WebBrowser 控件的 DocumentCompleted 事件,并根据大小设置图像样式。

例如:

1) 创建 Windows 窗体项目 2) 在设计模式下打开Form1,并在其上放置一个WebBrowser 控件。 3)双击表单的标题栏来处理表单的Load事件并使用以下代码:

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

4) 双击WebBrowser控件来处理其DocumentCompleed事件并使用以下代码:

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");
}

您将看到以下结果,而原始图像尺寸为 544x184:

enter image description here

注1

这只是您可以执行的操作的一个示例。您可以做出更明智的决定,例如检查图像尺寸是否小于浏览器尺寸,则无需应用任何缩放。

注2 - (这是我的选择)

如果您将 WebBrowser 控件设置为 support showing modern content 更好的图像样式是:

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

这样,当图像大于浏览器时,图像将适合浏览器。当浏览器足够大时,它也不会调整大小。

关于c# - Web 浏览器中的内容在 Windows 窗体应用程序中自动缩放时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46665491/

相关文章:

c# - 通过 VSTO 在 PowerPoint 设计器中捕获鼠标事件

c# - 从更大的二维集合中挑选一个子集?

c# - WPF - 在单元测试中引发 KeyEvent 触发器不起作用

c# - 我怎样才能有可选择的标签?

c# - Winforms:如何创建具有可变项目高度的列表框

c# - 为什么 MailDefinition 类需要 System.Web.UI.Control?

C# 多线程

java - 这是状态机的用例吗?如果是这样,您建议使用哪个开源软件?

c# - E pluribus unum : merge objects into one

c# - 在安装过程中获取应用程序路径