我正在尝试编写一个C#程序来播放跳棋。到目前为止,我已经完成了所有“浅”的事情,例如生成板和所有标签等。定义发件人动态添加的事件处理程序
我的问题是所有的控件都是动态添加的。所以我不能只是“双击”它们并且定义Button_Click事件要做什么。
这是我生成表单
public partial class formGameBoard : Form
{
private readonly int m_BoardSize;
private readonly string m_Player1Name;
private readonly string m_Player2Name;
private GameTile m_BlueTile;
private bool m_IsThereBlue;
public formGameBoard(int i_BoardSize, string i_Player1Name, string i_Player2Name)
{
m_BoardSize = i_BoardSize;
m_Player1Name = i_Player1Name;
m_Player2Name = i_Player2Name;
if (m_Player2Name == "(Computer)")
{
m_Player2Name = "Computer";
}
m_IsThereBlue = false;
InitializeComponent();
}
private void formGameBoard_Load(object sender, EventArgs e)
{
int SizeOfButton = 60;
int ButtonRowindex = 0;
int ButtonColindex = 0;
this.Size = new System.Drawing.Size(30 + m_BoardSize * SizeOfButton, 100 + m_BoardSize * SizeOfButton);
Button[,] PlayButtonArray = new Button[m_BoardSize, m_BoardSize];
for (ButtonRowindex = 0; ButtonRowindex < m_BoardSize; ButtonRowindex++)
{
for (ButtonColindex = 0; ButtonColindex < m_BoardSize; ButtonColindex++)
{
PlayButtonArray[ButtonRowindex, ButtonColindex] = new Button();
PlayButtonArray[ButtonRowindex, ButtonColindex].Size = new Size(SizeOfButton, SizeOfButton);
PlayButtonArray[ButtonRowindex, ButtonColindex].Left = 10 + ButtonRowindex * SizeOfButton;
PlayButtonArray[ButtonRowindex, ButtonColindex].Top = 50 + ButtonColindex * SizeOfButton;
if ((ButtonRowindex + ButtonColindex) % 2 == 0)
{
PlayButtonArray[ButtonRowindex, ButtonColindex].Enabled = false;
PlayButtonArray[ButtonRowindex, ButtonColindex].BackColor = Color.Gray;
}
this.Controls.Add(PlayButtonArray[ButtonRowindex, ButtonColindex]);
}
}
FillButtons(PlayButtonArray);
}
public void FillButtons(Button[,] ButtonMatrix)
{
int i, j;
for (i = 0; i < m_BoardSize; i++)
{
for (j = 0; j < m_BoardSize; j++)
{
if ((i + j) % 2 == 1)
{
if (j <= (m_BoardSize/2) - 2)
{
ButtonMatrix[i, j].Text = "O";
}
if (j > (m_BoardSize/2))
{
ButtonMatrix[i, j].Text = "X";
}
}
}
}
}
struct GameTile
{
int RowIndex;
int ColumnIndex;
}
}
}
我的问题是,所有的按钮都动态地添加。我没有拖放它们。我在表单加载时创建了它们。现在,当我点击一个按钮时,我想要发生一些事情。例如,我想让我点击的按钮将其颜色更改为蓝色。
我该怎么做?
您可以创建一个方法和挂钩与方法的按钮。例如。 button.OnClicked + = OnClicked –
您可以为该按钮或按钮创建代理OnCleick事件 – MethodMan