我有一个带 2 个显示器的 Windows 11 系统:
我想在另一台显示器上显示一个新的 WPF 窗口 - 这意味着在该显示器上当前未显示我的主应用程序。因此,如果我的主窗口在 4k 显示器上,那么我想在全高清显示器上显示新窗口。
新窗口应该显示我的网络摄像头的全屏视图。但不同的 DPI 设置会导致很难以正确的位置和大小显示全屏窗口。
我的 Window XAML 很简单,看起来像这样
<Window
x:Class="MyApp.Fullscreen"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="800"
Height="600"
AllowsTransparency="False"
Background="Black"
ResizeMode="NoResize"
ShowInTaskbar="False"
Topmost="True"
WindowStyle="None">
<Grid>
<Image Name="WebCam" />
</Grid>
</Window>
我是这样初始化的
var allSystemScreens = System.Windows.Forms.Screen.AllScreens;
var otherScreen = DetermineOtherScreen(allSystemScreens);
var window = new Fullscreen();
window.WindowStartupLocation = WindowStartupLocation.Manual;
window.Left = otherScreen.WorkingArea.Left;
window.Top = otherScreen.WorkingArea.Top;
window.Width = otherScreen.WorkingArea.Width;
window.Height = otherScreen.WorkingArea.Height;
window.Show();
但这不起作用。它没有在显示器上完全显示窗口,或者窗口比显示器大得多,并且正在延伸到第二个窗口。
我尝试了工作区域中的值。但它从来没有起作用。
我的应用程序支持每个显示器的 DPI 。我尝试应用从系统读取的比例因子,但无论我使用什么值 - 它的位置或大小都永远不正确。
如何正确做?或者有没有更简单或更好的方法来实现这一目标?也许不使用
WindowStartupLocation.Manual
。
首先获取当前显示主应用程序的显示器的比例因子,例如通过
VisualTreeHelper.GetDpi
方法
var dpiScale = VisualTreeHelper.GetDpi(mainWindow);
double scaleFactor = dpiScale.DpiScaleX;
现在尝试计算另一台显示器上全屏窗口的正确位置和大小(您还需要考虑两台显示器的比例因子!)
类似这样的:
var otherScreen = DetermineOtherScreen(allSystemScreens);
var otherScreenScaleFactor = VisualTreeHelper.GetDpi(otherScreen);
double otherScreenScale = otherScreenScaleFactor.DpiScaleX;
double left = otherScreen.WorkingArea.Left / otherScreenScale;
double top = otherScreen.WorkingArea.Top / otherScreenScale;
double width = otherScreen.WorkingArea.Width / otherScreenScale;
double height = otherScreen.WorkingArea.Height / otherScreenScale;
//save the scale factor of the main app's monitor to the fullscreen window size
width /= scaleFactor;
height /= scaleFactor;
window.Left = left;
window.Top = top;
window.Width = width;
window.Height = height;