如何在运行时允许用户创建新的 Picturebox Visual Studio C# Windows Forms Apps

How to at runtime allow a user to create a new Picturebox Visual Studio C# Windows Forms Apps

我正在尝试在 Visual Studio Windows Forms Apps C# 中创建一个表单,在其中,在运行时用户或操作员可以通过单击鼠标左键创建一个新的图片框,然后能够移动创建的每个图片框。

我真的不知道从哪里开始。有人有什么想法吗?

您可以在运行时添加表单元素:

var picture = new PictureBox
{
    Name = "pictureBox",
    Size = new Size(16, 16),
    Location = new Point(100, 100),
    Image = Image.FromFile("test.jpg"),

};
this.Controls.Add(picture);

之后,您可以使用鼠标事件移动它

要动态添加新的 PictureBox,您可以订阅事件 Form_MouseClick 并像这样创建 PictureBox:

public Form1()
{
    InitializeComponent();
    this.MouseClick += Form_MouseClick;
}

private void Form_MouseClick(object sender, MouseEventArgs e)
{
    PictureBox pictureBox = new PictureBox();
    // cursor location
    pictureBox.Location = new Point(e.X, e.Y);
    pictureBox.BackColor = Color.Red;
    this.Controls.Add(pictureBox);
}

要拖动和移动图片框,您还需要订阅事件MouseDownMouseUpMouseMove

这里有一个简单的demo,大家可以参考一下。

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;
}