【发布时间】:2015-09-05 04:18:42
【问题描述】:
编辑:我解决了。在下面的答案中查看我的修复。
我正在开发一个应用程序,它应该在连接到运行它的计算机的每个屏幕上打开一个小弹出窗口。在单个屏幕上执行非常简单(使用 WindowStartupLocation = CenterScreen),但在多个屏幕上执行却异常困难。
我当前的代码是这样的:
foreach (var s in Screen.AllScreens) //System.Windows.Forms.Screen
{
var b = s.Bounds;
var w = new PopupWindow();
var oW = w.Width; //Keep track of original size ...
var oH = w.Height;
w.Width = 0; //then set the size to 0, to avoid that the
w.Height = 0;//popup shows before it is correctly positioned
w.Show(); //Now show it, so that we can place it (when I
//tried to place it before showing, the window
//was always repositioned when Show() was called)
double dpiX = 1, dpiY = 1;
var presentationsource = PresentationSource.FromVisual(w);
if (presentationsource != null)
{
dpiX = presentationsource.CompositionTarget.TransformToDevice.M11;
dpiY = presentationsource.CompositionTarget.TransformToDevice.M22;
}
var aW = oW*dpiX; //Calculate the actual size of the window
var aH = oH*dpiY;
//***** THIS IS WRONG, SEE ANSWER *****
w.Left = (b.X + (b.Width / dpiX - aW) / 2); //Place it
w.Top = (b.Y + (b.Height / dpiY - aH) / 2);
//*************************************
w.Width = oW; //And set the size back to the original size
w.Height = oH;
}
这似乎只在主屏幕上有效。在其他屏幕上,窗口未正确居中。
我想这是因为我对 WPF 和 DPI 的了解非常有限,而且我可能做错了什么。有人能指出我正确的方向吗?
【问题讨论】:
-
您不应该使用代码手动将
Popup居中。您应该简单地使用Popup类的PlacementTarget和Placement属性。 -
对不起,我可能不清楚;它实际上不是“Popup”类。我正在使用“Window”(如代码所示)。此外,问题不是集中在“一个”屏幕上,而是集中在多个屏幕上。所以这实际上不是链接问题的重复。 :)
-
好的,我重新打开了这个问题。
标签: c# wpf centering multiple-monitors