使用DesktopDPIOverride时PointToScreen不正确

Shu*_*arg 15 c# windows winforms

将"更改所有项目的大小"滑块设置Control Panel\Appearance and Personalization\Display为较大(更改此注册表项HKEY_CURRENT_USER\Control Panel\Desktop\DesktopDPIOverride:) :导致Control.PointToScreen()方法错误计算.这可以使用Windows窗体中的以下Class1重现:

public class Class1 : Control
{
  protected override void OnPaint(PaintEventArgs e)
  {
    base.OnPaint(e);

    Draw(e.ClipRectangle, e.Graphics);
  }

  private void Draw(Rectangle rect, Graphics graphics)
  {
    Pen pen = new Pen(Color.Red);
    pen.Width = 2;

    graphics.DrawRectangle(pen, rect);
  }

  protected override void OnMouseDown(MouseEventArgs e)
  {
    base.OnMouseDown(e);

    Point p = this.PointToScreen(new Point(0, 0));

    ControlPaint.DrawReversibleFrame(new Rectangle(p, new Size(e.X, e.Y)), Color.Yellow, FrameStyle.Dashed);
  }

  protected override void OnMouseUp(MouseEventArgs e)
  {
    base.OnMouseUp(e);
    this.Invalidate();
  }
}
Run Code Online (Sandbox Code Playgroud)

在WinForm中使用此控件并单击它可以按预期工作.现在将"更改所有项目的大小"更改为"更大"并再次运行代码 - 代码不再按预期运行,PointToScreen方法返回(0,0)的错误值.

有人知道如何解决这个问题吗?非常感谢.

Ale*_*lex 2

听起来您需要使其 DPI 感知。你可以这样做

[DllImport("user32.dll")]
private static extern bool SetProcessDPIAware();

static void Main()
{
    SetProcessDPIAware();

}
Run Code Online (Sandbox Code Playgroud)