【发布时间】:2011-08-03 18:26:22
【问题描述】:
我了解,如果计算机未使用默认 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 空间,以便正确设置 Left 和 Top?
【问题讨论】:
-
不确定是否支持多显示器,但您可以仅使用 WPF(支持 DPI)将窗口正确定位在主屏幕上,而无需使用 Windows 窗体(不支持 DPI)系统参数类。相关属性会自动调整为不同的 DPI 设置。示例:window.Top = SystemParameters.FullPrimaryScreenHeight - (window.ActualHeight - SystemParameters.WindowCaptionHeight); //适用于Vista和Windows 7,不知道XP。
标签: .net wpf coordinates