在更高的DPI设置下将Screen.PrimaryScreen.WorkingArea转换为WPF尺寸
我的WPF应用程序中有以下function,用于将窗口调整为主屏幕的工作区域(整个屏幕减去任务栏):
private void Window_Loaded(object sender, RoutedEventArgs e) { int theHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height; int theWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width; this.MaxHeight = theHeight; this.MinHeight = theHeight; this.MaxWidth = theWidth; this.MinWidth = theWidth; this.Height = theHeight; this.Width = theWidth; this.Top = 0; this.Left = 0; }
只要机器的DPI设置为100%,这种方法效果很好。 但是,如果他们将DPI设置得更高,那么这不起作用,并且窗口会溢出屏幕。 我意识到这是因为WPF像素与“真实”屏幕像素不同,并且因为我使用WinForms属性来获取屏幕尺寸。
我不知道WPF等效于Screen.PrimaryScreen.WorkingArea。 我可以使用哪些东西,无论DPI设置如何都可以使用?
如果没有,那么我想我需要某种缩放,但我不知道如何确定要缩放多少。
如何修改我的function以考虑不同的DPI设置?
顺便说一下,如果你想知道为什么我需要使用这个函数而不是只是最大化窗口,那是因为它是一个无边框窗口(WindowStyle =“None”),如果你最大化这种类型的窗口,它覆盖了任务栏。
您可以从SystemParameters.WorkArea
属性获得已转换的工作区大小:
Top = 0; Left = 0; Width = System.Windows.SystemParameters.WorkArea.Width; Height = System.Windows.SystemParameters.WorkArea.Height;
在WPF中,您可以使用SystemParameters.PrimaryScreenWidth
和SystemParameters.PrimaryScreenHeight
属性来查找主要屏幕尺寸:
double width = SystemParameters.PrimaryScreenWidth; double height = SystemParameters.PrimaryScreenHeight;
如果你想获得两个屏幕的尺寸,你可以使用:
var primaryScreen = System.Windows.Forms .Screen .AllScreens .Where(s => s.Primary) .FirstOrDefault(); var secondaryScreen = System.Windows.Forms .Screen .AllScreens .Where(s => !s.Primary) .FirstOrDefault();
在此之后,您可以使用以达到宽度,高度等
primaryScreen.Bounds.Width
太长 ;)