编辑:我解决了。请参阅下面的答案中的我的修复。
我正在开发一个应用程序,它应该在连接到运行它的计算机的每个屏幕上打开一个小弹出窗口。在单个屏幕上足够简单(使用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的了解非常有限,而且我可能做错了什么。有人能指出我正确的方向吗?
答案 0 :(得分:1)
当然,我在这里发布后设法解决了这个问题。当我试图用DPI划分整个位置时,看起来我做了别的错误,这导致我走上了上面发布的错误路径。
放置表单的正确行应为此(所有其他代码都有效):
w.Left = (b.X + (b.Width - aW) / 2) / dpiX;
w.Top = (b.Y + (b.Height - aH) / 2) / dpiX;
但是,我仍然认为这是一个简单任务的代码,所以如果有人有更好的想法,请告诉我!
所以这是我现在使用的(工作)代码:
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 ps = PresentationSource.FromVisual(w);
if (ps != null)
{
dpiX = ps.CompositionTarget.TransformToDevice.M11;
dpiY = ps.CompositionTarget.TransformToDevice.M22;
}
var aW = oW*dpiX; //Calculate the actual size of the window
var aH = oH*dpiY;
w.Left = (b.X + (b.Width - aW) / 2) / dpiX;
w.Top = (b.Y + (b.Height - aH) / 2) / dpiX;
w.Width = oW; //And set the size back to the original size
w.Height = oH;
}
答案 1 :(得分:-1)
var centers =
System.Windows.Forms.Screen.AllScreens.Select(
s =>
new
{
Left = s.Bounds.X + (s.WorkingArea.Right - s.WorkingArea.Left)/2,
Top = s.Bounds.Y + (s.WorkingArea.Bottom - s.WorkingArea.Top)/2
});
foreach (var c in centers)
{
var w = new Window1();
w.Left = c.Left - w.Width/2;
w.Top = c.Top - w.Height/2;
w.Show();
}