如何将位置保存在静态变量(e.X,e.Y)中

时间:2018-12-18 20:54:58

标签: c#

我使用鼠标上移和鼠标下移方法绘制对象,因此可以通过e.X和e.Y获取它们的位置。因此,我该如何保存每个绘制项目的位置。

1 个答案:

答案 0 :(得分:1)

您可以创建私有变量以跟踪开始和结束位置,然后使用从MouseDown参数获得的MouseUpMouseEventArgs事件中的值来更新它们。您还可以创建一个List<Rectangle>来跟踪所有绘制的矩形,并在MouseUp事件中添加到其中:

// Variables to keep track of the current drawing
private Point startLocation;
private Point endLocation;

// A list to hold all drawings
private List<Rectangle> drawnItems = new List<Rectangle>();

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    // Capture the start point
    startLocation = new Point(e.X, e.Y);
}

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
    // Capture the end point
    endLocation = new Point(e.X, e.Y);

    // Save this rectangle in our list
    drawnItems.Add(new Rectangle(startLocation,
        new Size(endLocation.X - startLocation.X, endLocation.Y - startLocation.Y)));

    // Display a message
    var message = new StringBuilder();

    message.AppendLine("You drew a rectangle starting at point: " +
                    $"{startLocation} and ending at point: {endLocation}\n");

    message.AppendLine("Here are all the rectangles you've drawn:");

    for(int i = 0; i < drawnItems.Count; i++)
    {
        message.AppendLine($" {i + 1}. " + drawnItems[i]);
    }

    MessageBox.Show(message.ToString());
}

输出 ...绘制4个矩形后:

enter image description here