如何在 c# 中创建事件

本文关键字:创建 事件 | 更新日期: 2023-09-27 18:31:00

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

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;

面板会像它应该的那样改变颜色,但是我将如何使用数组创建像鼠标输入这样的事件?????

如何在 c# 中创建事件

您需要

将事件附加到您正在生成的每个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都有自己的处理程序,用于以这种方式进入/退出鼠标,并且可以进行处理。