Windows显示设置导致Screen.PrimaryScreen.Bounds.Width不正确

时间:2014-06-20 09:54:27

标签: c# .net winforms

我们制作了一个使用条款应用程序,用于填充用户的整个屏幕,并将文本置于屏幕中间。

我们已经通过将位置设置为Screen.PrimaryScreen.Bounds.X + 10然后将宽度设置为Width = Screen.PrimaryScreen.Bounds.Width - 10,来实现这些目标 - 这有效地提供了10px填充以及其他完美的中心文本。

然而问题是,当用户将“更容易阅读屏幕上的内容”选项更改为125%时,Bounds.Width值不正确,并且文本离开屏幕。

Make it easier to read what's on your screen, set to 125%

有趣的是,如果你将它设置为'更大--150%',它会很好地计算屏幕宽度。

我也尝试过使用Screen.PrimaryScreen.WorkingArea.Width,但这只会给出相同(不正确)的结果。

请问有解决方法吗?谢谢

(edit)以下是生成元素的完整代码:

protected override void OnLoad(System.EventArgs e) {
    this._webBrowser = new WebBrowser {
      IsWebBrowserContextMenuEnabled = false,
      AllowWebBrowserDrop = false,
      Location = new Point(Screen.PrimaryScreen.Bounds.X + 10, Screen.PrimaryScreen.Bounds.Y + 150),
      Width = Screen.PrimaryScreen.Bounds.Width - 20,
      ScrollBarsEnabled = true,
      DocumentText = "<html><body><div>" + agreement.Terms + "</div></body></html>"
    };
}

1 个答案:

答案 0 :(得分:3)

看不见(总是发布代码片段),这是因为您将代码放在错误的位置。您正在Form类的构造函数中设置大小。然后,由于表单最初设计为96 DPI,因此您的表单会自动缩放以适应较大的DPI设置。其中增长表格的比例为125%,现在太大了。

重新调整表单后,必须在之后设置的大小。 Load事件处理程序是最好的机会,实际上是实际需要Load的几个原因之一。此时,已应用缩放,但窗口尚未可见。因此,覆盖大小和位置属性的最佳位置。修正:

    protected override void OnLoad(EventArgs e) {
        var scr = Screen.FromPoint(this.Location);
        this.Bounds = new Rectangle(
            scr.WorkingArea.Left + 10, scr.WorkingArea.Top,
            scr.WorkingArea.Width - 20, scr.WorkingArea.Bottom);
        base.OnLoad(e);
    }

编辑后,您应该使用屏幕坐标来设置控件的位置和大小属性。子控件的位置与其父客户区相对,并且必须位于其内部。修正:

this._webBrowser = new WebBrowser {
    Location = new Point(10, 10),
    Width = this.ClientSize.Width - 20,
    Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Top,
    // etc...
};

设置锚点可确保它与父级一起调整大小,可能是您想要的。此代码属于构造函数,而不属于OnLoad(),因为现在您执行希望浏览器与表单一起重新调整。如果您使用过设计器,那么您将自动获得正确的代码。