我正在初始化一个PictureBox
数组。问题是,我不能每个人都添加个人EventHandler
。我在for循环中有这段代码:
picBoxs[i] = new PictureBox();
picBoxs[i].Anchor = AnchorStyles.None;
picBoxs[i].Location = new Point(x, y);
picBoxs[i].Size = new Size(104, 104);
picBoxs[i].SizeMode = PictureBoxSizeMode.Normal;
picBoxs[i].BorderStyle = BorderStyle.FixedSingle;
//this.picBoxs[i].Click += new System.EventHandler(this.picBoxs_Click); //Single EventHandler for all PictureBox(s)
this.picBoxs[i].Click += new System.EventHandler(this.picBoxs[i]_Click); //Generates error
我想要picBoxs1_Click()
,picBoxs2_Click()
,picBoxs3_Click()
...(依此类推)。因为每个EventHandler
我需要PictureBox
。我可以毫无疑问地使EventHandler
,picBox_Click()
成为常规,但是这样做我为每个PictureBox
获得了一个方法,点击不同的PictureBox
后我就无法做出不同的事情。任何想法将不胜感激。
提前致谢...
修改 我想,当我点击PictureBox时,会出现一个消息框,告诉我一个2D数组的索引。说我的图片箱安排如下:
picBox0 picBox1 picBox2
picBox3 picBox4 picBox5
点击picBox2后:MessageBox会说“[0] [2]”,与点击picBox4相同:MessageBox会说“[1] [1]”等等......
答案 0 :(得分:2)
使用单个事件处理程序,如下所示:
this.picBoxs[i].Click += picBoxs_Click;
在该事件处理程序中,您可以查找有关您的图片框的信息:
void picBoxs_Click(object sender, EventArgs e)
{
var box = sender as PictureBox;
int i = Array.IndexOf(picBoxs, box);
int columnCount = 3;
int row = i / columnCount;
int col = i % columnCount;
Messagebox.Show(string.Format("[{0}][{1}]", row, col));
}
答案 1 :(得分:1)
这里没有变得复杂,这对你来说是一个简单的解决方案
首先,声明一个具有每个框大小的全局const
const int BOX_SIZE = 128;
然后创建所有这些框
this.picBoxs[i].Click += new System.EventHandler(Boxes_Click);
picBoxs[i].Location = new Point(x*BOX_SIZE, y*BOX_SIZE);
picBoxs[i].Size = new Size(BOX_SIZE,BOX_SIZE);
最后是事件处理程序:
void Boxes_Click(object sender, EventArgs e)
{
PictureBox theBox = sender as PictureBox;
if(theBox != null)
{
MessageBox.Show("Box was clicked, x: {0} y:{1}",
theBox.Location.X / BOX_SIZE,
theBox.Location.Y / BOX_SIZE);
}
}
如果这不适合您,请创建一个派生PictureBox的类,并添加一个名为Coordinates的属性,或者您可以在其中存储Box的坐标。
class MyPictureBox : PictureBox
{
public Point Coordinates { get; set;}
}
然后:
int size_w = 128;
int size_h = 128;
...
MyPictureBox[] picBoxs = new MyPictureBox[1000];
...
picBoxs[i].Click += new System.EventHandler(Boxes_Click);
picBoxs[i].Coordinates = new Point(x,y);
picBoxs[i].Position = new Point(x * size_w, y*size_h);
picBoxs[i].Size = new Size(size_w, size_h);
...
void Boxes_Click(object sender, EventArgs e)
{
MyPictureBox theBox = sender as MyPictureBox;
if(theBox != null)
{
MessageBox.Show("Box was clicked, x: {0} y:{1}",
theBox.Coordinates.X,
theBox.Coordinates.Y);
}
}