如何在c#中创建事件

时间:2013-09-11 14:05:09

标签: c# events

好的我用这段代码创建了一个棋盘:

int numBlocks = 8;
Panel[,] chessBoardPanels = new Panel[numBlocks, numBlocks];
for (int iRow = 0; iRow < numBlocks; iRow++)
    for (int iColumn = 0; iColumn < numBlocks; iColumn++)
    {
        Panel p = new Panel();
        //set size
        p.Size = new Size(50, 50);
        //set back colour
        p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
        //set location
        p.Location = new Point(50 * iRow, 50 * iColumn);
        chessBoardPanels[iRow, iColumn] = p;
        groupBox1.Controls.Add(p);
    }

当我使用命令时:

 chessBoardPanels[1,1].BackColor=Color.Red;

面板会改变它的颜色,但是如何使用数组创建像鼠标一样的事件?????

1 个答案:

答案 0 :(得分:1)

您需要将事件附加到您正在生成的每个Panel对象上,这里是我正在谈论的内容的粗略示例

for (int iRow = 0; iRow < numBlocks; iRow++)
{
    for (int iColumn = 0; iColumn < numBlocks; iColumn++)
    {
        Panel p = new Panel();

        // set size, position, etc, then:

        p.MouseEnter += (s,e) => { (s as Panel).BackColor=Color.Red; }
        p.MouseLeave += (s,e) => { (s as Panel).BackColor=Color.Black; }

        // the panel is born of this color
        p.BackColor = Color.Black; // .. or any color you put in MouseLeave
        groupBox1.Controls.Add(p);  
    }
}

每个Panel都有自己的处理程序,鼠标以这种方式进入/退出,并且可以处理。