如何使用C#确定屏幕的宽度/高度

30

我希望能根据用户屏幕的最大宽度/高度来动态设置 Window 的宽度和高度。如何通过编程确定这个值?


1
最大化你的窗口不可行吗? - Lazarus
@Lazarus:不,不是我想处理的情况。 - Shamim Hafiz - MSFT
6个回答

42

对于主屏幕:

System.Windows.SystemParameters.PrimaryScreenWidth
System.Windows.SystemParameters.PrimaryScreenHeight

(请注意,还有一些其他与主屏幕相关的属性取决于各种因素,如Full*Maximised*)

虚拟屏幕:

SystemParameters.VirtualScreenWidth
SystemParameters.VirtualScreenHeight

1
基于当前分辨率怎么样?如何获取它? - Shamim Hafiz - MSFT
2
我认为这确实使用了当前的分辨率,你试过了吗? - H.B.
终于有了这个问题的答案!当用户在应用程序打开时更改缩放比例时,VirtualScreenWidth[Height]是否不会更新?在Win10上,似乎必须重新启动应用程序才能重新填充这些值。 - Hashman
@Hashman:对此无法提供任何信息,甚至没有win 10的设置。 - H.B.

14
如果您想获取程序所在显示器的具体尺寸(如果有人同时运行多个显示器),您还可以使用以下方法:
var helper = new WindowInteropHelper(this); //this being the wpf form 
var currentScreen = Screen.FromHandle(helper.Handle);

这将返回一个引用程序正在运行的监视器的屏幕对象。从那里,你可以使用 currentScreen.Bounds.Width / Height 属性(全尺寸)或者 currentScreen.WorkingArea.Width / Height 属性(减去任务栏等)取决于你需要什么。


9

使用 Screen 对象

Screen.PrimaryScreen.Bounds.Width

2
您可以使用 SizeChanged 事件。
SizeChanged="MyWindow_SizeChanged"

然后在你的事件处理程序中,
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
    if (this.MinWidth > 0 && this.MinHeight > 0)
    {
        double heightScaleFactor = e.NewSize.Height / this.MinHeight;
        double widthScaleFactor = e.NewSize.Width / this.MinWidth;            
        mainGrid.LayoutTransform = new ScaleTransform(heightScaleFactor, widthScaleFactor);
    }
}

MainGridMyWindow 中所有内容的容器。


3
不确定这如何回答问题。 - Lazarus
这是一个有效的帖子,但正如Lazarus所提到的那样.. "它没有回答问题" :) - Shamim Hafiz - MSFT

2

当我使用Ranorex Studio 8.0.1+git.8a3e1a6f时,在Windows 10 Enterprise上,我无法在.NET 4.0.30319.42000下使用以上任何解决方案。因此,我使用了以下代码:

using WinForms = System.Windows.Forms;
[…]
                SetWindowPos(processes[0].MainWindowHandle,
                    0,
                    y,
                    x,
                    WinForms.SystemInformation.PrimaryMonitorSize.Width,
                    WinForms.SystemInformation.PrimaryMonitorSize.Height,
                    SWP.SHOWWINDOW);

谢谢伙计,我也在使用Ranorex,并尝试适应其他答案,但你说得很对。 - Ewan

0
你可以获取屏幕的高度和宽度:
int height = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height;
int width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width;

然后将窗口的 HeightWidth 属性设置为初始化时的那些值。
this.Height = height;
this.Width = width;

获取WinForms或ASP .NET中屏幕的高度和宽度。没有麻烦,除非您的项目不是WinForm项目,否则您需要在项目中引用System.Windows.Forms程序集。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接