我希望能根据用户屏幕的最大宽度/高度来动态设置 Window
的宽度和高度。如何通过编程确定这个值?
对于主屏幕:
System.Windows.SystemParameters.PrimaryScreenWidth
System.Windows.SystemParameters.PrimaryScreenHeight
(请注意,还有一些其他与主屏幕相关的属性取决于各种因素,如Full*
和Maximised*
)
虚拟屏幕:
SystemParameters.VirtualScreenWidth
SystemParameters.VirtualScreenHeight
var helper = new WindowInteropHelper(this); //this being the wpf form
var currentScreen = Screen.FromHandle(helper.Handle);
这将返回一个引用程序正在运行的监视器的屏幕对象。从那里,你可以使用 currentScreen.Bounds.Width
/ Height
属性(全尺寸)或者 currentScreen.WorkingArea.Width
/ Height
属性(减去任务栏等)取决于你需要什么。
使用 Screen 对象
Screen.PrimaryScreen.Bounds.Width
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);
}
}
MainGrid
是 MyWindow
中所有内容的容器。
当我使用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);
int height = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height;
int width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width;
Height
和 Width
属性设置为初始化时的那些值。this.Height = height;
this.Width = width;
获取WinForms或ASP .NET中屏幕的高度和宽度。没有麻烦,除非您的项目不是WinForm项目,否则您需要在项目中引用System.Windows.Forms
程序集。