【问题标题】:How to store locations properly如何正确存储位置
【发布时间】:2021-07-25 10:22:48
【问题描述】:

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

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-studio picturebox windows-forms-designer


    【解决方案1】:

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

    首先,将字典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();
        }
    }
    

    【讨论】:

    • 太棒了。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    相关资源
    最近更新 更多