将System.Drawing.Points

时间:2015-10-05 19:57:36

标签: c# wpf winforms system.drawing mousemove

我遇到过以下代码,它使用System.Drawing.Size类的构造函数来添加两个System.Drawing.Point对象。

// 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);

我认为在最后一个语句中使用+ new Size(mpWF)是一个黑客,因为当我阅读上面的代码时,它减慢了我的速度,因为我没有立即理解发生了什么。

我尝试解释最后一句话如下:

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

但它不起作用,因为没有为两个System.Drawing.Point对象定义添加。有没有其他方法可以在两个Point对象上执行添加,这比原始代码更直观?

2 个答案:

答案 0 :(得分:4)

为它创建一个扩展方法:

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

用法:

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

答案 1 :(得分:0)

我在Cody Gray的this回答中找到了解决方案。

请注意,在我发布问题后,相关问题才出现在右侧面板上。