Search code examples
c#wpfwinformssystem.drawingmousemove

Adding together System.Drawing.Points


I have come across the following code that uses the constructor of the System.Drawing.Size class to add two System.Drawing.Point objects.

// System.Drawing.Point mpWF contains window-based mouse coordinates
// extracted from LParam of WM_MOUSEMOVE message.

// Get screen origin coordinates for WPF window by passing in a null Point.
System.Windows.Point originWpf = _window.PointToScreen(new System.Windows.Point());

// Convert WPF doubles to WinForms ints.
System.Drawing.Point originWF = new System.Drawing.Point(Convert.ToInt32(originWpf.X),
    Convert.ToInt32(originWpf.Y));

// Add WPF window origin to the mousepoint to get screen coordinates.
mpWF = originWF + new Size(mpWF);

I consider the use of the + new Size(mpWF) in the last statement a hack because when I was reading the above code, it slowed me down as I did not immediately understand what was going on.

I tried deconstructing that last statement as follows:

System.Drawing.Point tempWF = (System.Drawing.Point)new Size(mpWF);
mpWF = originWF + tempWF;  // Error: Addition of two Points not allowed.

But it didn't work as addition is not defined for two System.Drawing.Point objects. Is there any other way to perform addition on two Point objects that is more intuitive than the original code?


Solution

  • Create an Extension Method:

    public static class ExtensionMethods
    {
        public static Point Add(this Point operand1, Point operand2)
        {
            return new Point(operand1.X + operand2.X, operand1.Y + operand2.Y);
        }
    }
    

    Usage:

     var p1 = new Point(1, 1);
     var p2 = new Point(2, 2);
     var result = p1.Add(p2);