多显示器环境下WPF窗口页面切换时保持在当前工作显示器居中的问题
问题根因
你当前的实现始终读取主显示器的分辨率参数计算居中位置,完全忽略了窗口当前所处的显示器坐标,所以只要调用方法就会强制切回主显示器。
解决方案
第一步:添加依赖引用
你需要在项目中添加两个程序集引用:
System.Windows.FormsSystem.Drawing
第二步:修正居中方法
替换你的原有代码为如下实现:
public static void CenterWindowOnScreen(double width, double height) { var mainWindow = App.Current.MainWindow; // 获取窗口当前所在的显示器 var windowHandle = new System.Windows.Interop.WindowInteropHelper(mainWindow).Handle; var currentScreen = System.Windows.Forms.Screen.FromHandle(windowHandle); // 获取当前显示器的DPI缩放比例,适配高DPI设备 var dpi = VisualTreeHelper.GetDpi(mainWindow); // 换算为WPF设备无关单位 double screenLeft = currentScreen.Bounds.Left / dpi.DpiScaleX; double screenTop = currentScreen.Bounds.Top / dpi.DpiScaleY; double screenWidth = currentScreen.WorkingArea.Width / dpi.DpiScaleX; double screenHeight = currentScreen.WorkingArea.Height / dpi.DpiScaleY; // 计算居中坐标 mainWindow.Left = screenLeft + (screenWidth / 2) - (width / 2); mainWindow.Top = screenTop + (screenHeight / 2) - (height / 2); }
注意事项
- 调用该方法时需确保主窗口已完成初始化加载,否则无法获取正确的窗口句柄
- 如果页面切换时窗口尺寸会动态调整,建议在窗口
SizeChanged事件触发后再调用居中方法,避免计算偏差
内容的提问来源于stack exchange,提问作者Daniel Issac
相关产品推荐
相关产品推荐

