如何在UWP应用中获取所有物理显示器的边界?
在UWP中获取物理显示器边界并指定启动显示器
如果你之前用WinForms的System.Windows.Forms.Screen.AllScreens来获取多显示器信息,转到UWP后确实需要换一套API——UWP里我们可以用DisplayManager类来枚举所有物理显示器,还能实现让应用在指定的竖屏显示器启动的需求,下面一步步来:
一、获取所有物理显示器的边界
UWP的DisplayManager是专门用来管理显示设备的API,它能拿到所有物理显示器的位置、尺寸和方向信息。
首先需要添加对应的命名空间:
using Windows.Devices.Display.Core; using Windows.Foundation; using Windows.UI.ViewManagement; using System.Linq;
然后用这段代码枚举所有显示器:
// 获取DisplayManager实例 var displayManager = DisplayManager.GetCurrent(); // 枚举所有物理显示器 var allDisplays = displayManager.DisplayInfos; foreach (var display in allDisplays) { // 获取显示器在虚拟桌面中的边界(X/Y是左上角坐标,Width/Height是尺寸) Rect screenBounds = display.ScreenRect; // 判断是否为竖屏显示器 bool isPortrait = display.CurrentOrientation is DisplayOrientations.Portrait or DisplayOrientations.PortraitFlipped; // 输出调试信息,你可以根据需求存下这些数据 System.Diagnostics.Debug.WriteLine($"显示器: 位置({screenBounds.X}, {screenBounds.Y}),尺寸({screenBounds.Width}x{screenBounds.Height}),是否竖屏: {isPortrait}"); }
这里的ScreenRect和WinForms里Screen.Bounds的逻辑一致,都是基于虚拟桌面的坐标系,能准确反映每台显示器的位置和大小。
二、让应用在指定竖屏显示器启动
要实现这个需求,我们需要在应用启动阶段(比如App.xaml.cs的OnLaunched方法里)找到目标竖屏显示器,然后调整应用窗口的位置和大小。
修改App.xaml.cs中的启动逻辑:
protected override async void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { rootFrame.Navigate(typeof(MainPage), e.Arguments); } Window.Current.Activate(); // 等待窗口初始化完成(简单延迟,也可以用CoreWindow的Activated事件替代) await Task.Delay(100); // 尝试移动应用到竖屏显示器 MoveAppToTargetPortraitDisplay(); } } private void MoveAppToTargetPortraitDisplay() { var displayManager = DisplayManager.GetCurrent(); // 筛选出所有竖屏显示器 var portraitDisplays = displayManager.DisplayInfos .Where(d => d.CurrentOrientation is DisplayOrientations.Portrait or DisplayOrientations.PortraitFlipped) .ToList(); if (portraitDisplays.Count == 0) { System.Diagnostics.Debug.WriteLine("未检测到竖屏显示器"); return; } // 这里取第一个竖屏显示器,如果有多台可以根据位置/ID筛选 var targetDisplay = portraitDisplays.First(); Rect targetRect = targetDisplay.ScreenRect; var currentView = ApplicationView.GetForCurrentView(); // 设置应用窗口的首选大小为显示器尺寸 currentView.PreferredLaunchViewSize = new Size(targetRect.Width, targetRect.Height); currentView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize; // 尝试将窗口移动到目标显示器的区域 bool moveSuccess = currentView.TryMoveViewToRect(targetRect); if (!moveSuccess) { System.Diagnostics.Debug.WriteLine("无法将应用移动到目标显示器,可能受系统限制"); } }
注意事项
- 版本兼容性:
DisplayManager是从Windows 10 1703(Creators Update,版本号10.0.15063.0)开始支持的,所以你的UWP项目最低版本要设置为这个版本或更高。 - 窗口移动限制:
TryMoveViewToRect可能会失败(比如系统不允许跨显示器移动,或者显示器状态变化),所以一定要处理失败的情况。 - 默认方向设置:你可以在
Package.appxmanifest里把应用的默认显示方向设为“Portrait”,这样应用启动时就是竖屏状态,更符合需求。
内容的提问来源于stack exchange,提问作者Chris Lees
相关产品推荐
相关产品推荐

