我知道如果计算机没有使用默认的DPI设置,WPF坐标与“真实”屏幕坐标(像素坐标)是不同的。在我的程序中,我想要(1)找出一个WPF窗口位于哪个显示器上,以及(2)在同一显示器的左下角打开另一个窗口。我听说 WPF 没有类似于Screen的等效物,因此我使用WinForms版本,如下所示,在默认的96 DPI下运行良好:
public void ChooseInitialPosition(Window w) // w is some other window
{
var scr = System.Windows.Forms.Screen.FromRectangle(
new System.Drawing.Rectangle((int)w.Left, (int)w.Top, (int)w.Width, (int)w.Height))
.WorkingArea;
this.Left = scr.Right - Width;
this.Top = scr.Bottom - Height;
}
但是在其他DPI下,这两个步骤都会出现错误,并且可能将窗口完全移出屏幕。
到目前为止,看起来我可以使用Visual.PointToScreen来完成第一部分:
var p1 = w.PointToScreen(new Point(0,0));
var p2 = w.PointToScreen(new Point(w.Width,w.Height));
var scr = System.Windows.Forms.Screen.FromRectangle(
new System.Drawing.Rectangle((int)p1.X, (int)p1.Y, (int)(p2.X - p1.X), (int)(p2.Y - p1.Y))).WorkingArea;
我不确定这是否完全正确,因为它可能没有正确考虑边界。但第二部分更加重要。我如何将屏幕矩形“scr”转换为WPF空间,以便正确设置左和上?