WPF: Converting between screen coordinates and WPF coordinates

后端 未结 2 1818
孤独总比滥情好
孤独总比滥情好 2020-12-29 09:26

I understand that WPF coordinates are different from \"real\" screen coodinates (pixel coordinates) if the computer is not using the default DPI setting. In my program I wan

相关标签:
2条回答
  • 2020-12-29 10:08

    Does this work if you place it in the code-behind for your Window?

    protected override void OnContentRendered(System.EventArgs e)
    {
        base.OnContentRendered(e);
        MoveToLowerRightCorner();
    }
    
    private void MoveToLowerRightCorner()
    {
        var workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
        var transform = PresentationSource.FromVisual(this).CompositionTarget.TransformFromDevice;
        var corner = transform.Transform(new Point(workingArea.Right, workingArea.Bottom));
        this.Left = corner.X - this.ActualWidth;
        this.Top = corner.Y - this.ActualHeight;
    }
    
    0 讨论(0)
  • 2020-12-29 10:27
    1. Which screen a WPF window is on:

      private static Screen GetScreen(Window window)
      {
         return Screen.FromHandle(new WindowInteropHelper(window).Handle);
      }
      
    2. Open another window in the bottom-left corner of the same screen:

      static Point RealPixelsToWpf(Window w, Point p)
      {
          var t = PresentationSource.FromVisual(w).CompositionTarget.TransformFromDevice;
          return t.Transform(p);
      }
      private static void SetPositionBottomLeftCorner(Window sourceWindow, Window targetWindow)
      {
          var workingArea = GetScreen(sourceWindow).WorkingArea;
          var corner = RealPixelsToWpf(sourceWindow, new Point(workingArea.Left, workingArea.Bottom));
          targetWindow.Left = corner.X;
          targetWindow.Top = corner.Y - targetWindow.ActualHeight;
      }
      
    0 讨论(0)
提交回复
热议问题