首页 > 解决方案 > 如何正确存储位置

问题描述

我有这个表单,它允许用户通过鼠标移动单击并拖动它们来创建图片框。每次添加图片框或将图片框移动到新位置时,如何存储图片框所在位置的坐标(位置)?我正在尝试将它们作为导出字符串存储在列表中。

private void Form_MouseClick(object sender, MouseEventArgs e)
{
    // create new control
    PictureBox pictureBox = new PictureBox();
    pictureBox.Location = new Point(e.X, e.Y);
    pictureBox.BackColor = Color.Red;
    this.Controls.Add(pictureBox);
    // bind event for each PictureBox
    pictureBox.MouseDown += pictureBox_MouseDown;
    pictureBox.MouseUp += pictureBox_MouseUp;
    pictureBox.MouseMove += pictureBox_MouseMove;
}


Point mouseDownPoint = Point.Empty;
Rectangle rect = Rectangle.Empty;
bool isDrag = false;

private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        mouseDownPoint = e.Location;
        rect = (sender as PictureBox).Bounds;
    }
}

private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        if (isDrag)
        {
            isDrag = false;
            (sender as PictureBox).Location = rect.Location;
            this.Refresh();
        }
        reset();
    }
}

private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        isDrag = true;
        rect.Location = this.PointToClient((sender as PictureBox).PointToScreen(new Point(e.Location.X - mouseDownPoint.X, e.Location.Y - mouseDownPoint.Y)));
        this.Refresh();
    }
}

private void reset()
{
    mouseDownPoint = Point.Empty;
    rect = Rectangle.Empty;
    isDrag = false;
}

标签: c#visual-studiopictureboxwindows-forms-designer

解决方案


要保存每个图片框的位置,可以定义一个字典来保存键值对。

首先,将字典定义box_location_Pairs为全局变量。

然后在“单击创建新图片框”时将新项目添加到字典中。

Dictionary<PictureBox, Point> box_location_Pairs = new Dictionary<PictureBox, Point>();

// ...

private void Form_MouseClick(object sender, MouseEventArgs e)
{
    PictureBox pictureBox = new PictureBox();
    pictureBox.Location = new Point(e.X, e.Y);
    box_location_Pairs.Add(pictureBox, pictureBox.Location);
    // ...
}

如果图片框被移动,修改它的值。

private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        if (isDrag)
        {
            isDrag = false;
            (sender as PictureBox).Location = rect.Location;
            box_location_Pairs[sender as PictureBox] = rect.Location; // modifty key-value pair
            this.Refresh();
        }
        reset();
    }
}

推荐阅读