You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多显示器环境下WPF窗口页面切换时保持在当前工作显示器居中的问题

问题根因

你当前的实现始终读取主显示器的分辨率参数计算居中位置,完全忽略了窗口当前所处的显示器坐标,所以只要调用方法就会强制切回主显示器。

解决方案

第一步:添加依赖引用

你需要在项目中添加两个程序集引用:

  • System.Windows.Forms
  • System.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 16:54:00