引用多个实例化的图片框

本文关键字:实例化 引用 | 更新日期: 2023-09-27 17:57:37

我对C#很陌生,但如果我的语法不准确,请耐心学习。我可以用一个按钮创建一个图片框,它会出现在屏幕上。然后我可以用鼠标向下/鼠标移动功能在屏幕上移动它。然后,我点击按钮实例化另一个要创建的图片框,也可以移动这个图片框,但当我试图移动第一个图片框时,第二个图片框却移动了,变得疯狂。有没有一种方法可以在实例化时引用或标记框,这样当我点击其中任何一个框时,我就可以在屏幕上移动它们?

public partial class Form1 : Form
{
    Point MP;
    private static Control PB;        
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        int picSizeX = Properties.Resources.police.Width / 3;
        int picSizeY = Properties.Resources.police.Height / 3;
        PictureBox pb = new PictureBox();
        pb.Location = new Point(100, 100);
        pb.Size = new Size(picSizeX, picSizeY);
        pb.Image = new Bitmap(Properties.Resources.police);
        pb.SizeMode = PictureBoxSizeMode.StretchImage;
        Controls.Add(pb);
        pb.Tag = "veh";
        PB = pb;
        pb.MouseDown += Pb_MouseDown;
        pb.MouseMove += Pb_MouseMove;
        pb.MouseHover += Pb_MouseHover;
    }
    private void Pb_MouseHover(object sender, EventArgs e)
    {
        PB.MouseHover += PB_MouseHover;
    }
    private void PB_MouseHover(object sender, EventArgs e)
    {
    }
    private void Pb_MouseDown(object sender, MouseEventArgs e)
    {
        MP = e.Location;
    }
    private void Pb_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
           PB.Left = e.X + PB.Left - MP.X;
           PB.Top = e.Y + PB.Top - MP.Y;
        }
    }
}

引用多个实例化的图片框

实际上不需要在类级别拥有Control。

在事件方法中,有一个名为object sender的参数,该参数包含对引发事件的控件/对象的引用。

Point MP;
//private Control PB; //commented out as it is not required
public Form1()
{
    InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
     int picSizeX = Properties.Resources.police.Width / 3;
     int picSizeY = Properties.Resources.police.Height / 3;
     PictureBox pb = new PictureBox();
     pb.Location = new Point(100, 100);
     pb.Size = new Size(picSizeX, picSizeY);
     pb.Image = new Bitmap(Properties.Resources.police);
     pb.SizeMode = PictureBoxSizeMode.StretchImage;
     Controls.Add(pb);
     pb.Tag = "veh";
     //PB = pb;
     pb.MouseDown += Pb_MouseDown;
     pb.MouseMove += Pb_MouseMove;
     pb.MouseHover += Pb_MouseHover;
}
private void Pb_MouseHover(object sender, EventArgs e)
{
     Control pbObj = sender as PictureBox; //sender refers to control that raised the event
     pbObj.MouseHover += PB_MouseHover;
}
private void PB_MouseHover(object sender, EventArgs e)
{
}
private void Pb_MouseDown(object sender, MouseEventArgs e)
{
    MP = e.Location;
}
private void Pb_MouseMove(object sender, MouseEventArgs e)
{
     Control pbObj = sender as PictureBox; //sender refers to control that raised the event
     if (e.Button == MouseButtons.Left)
     {
         pbObj.Left = e.X + pbObj.Left - MP.X;
         pbObj.Top = e.Y + pbObj.Top - MP.Y;
     }
}