我正在研究这个项目,现在意识到我从未真正使用过“启用”/“禁用”功能,现在我想禁用特定按钮,而其他按钮仍然可以运行! (希望重启按钮在游戏结束后仍然有效)
有人可以帮我吗? 在此先感谢您的任何答复!
private void button_click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (turn)
b.Text = "X";
else
b.Text = "O";
turn = !turn;
b.Enabled = false;
checkForWinner();
}
private void checkForWinner()
{
bool there_is_a_winner = false;
if ((A1.Text == A2.Text) && (A2.Text == A3.Text) && (!A1.Enabled))
there_is_a_winner = true;
else if ((B1.Text == B2.Text) && (B2.Text == B3.Text) && (!B1.Enabled))
there_is_a_winner = true;
else if ((C1.Text == C2.Text) && (C2.Text == C3.Text) && (!C1.Enabled))
there_is_a_winner = true;
if (there_is_a_winner)
{
disableButtons();
String winner = "";
if (turn)
winner = "O";
else
winner = "X";
MessageBox.Show(winner + "Wins!", "Yay!");
}//end if
}// End Check For Winner
private void disableButtons()
{
foreach (Control c in Controls)
{
if (c.GetType() == typeof(Button))
{
Button b = (Button)c;
b.Enabled = false;
}//end foreach
}
}
答案 0 :(得分:0)
尝试
private void disableButtons()
{
for (int x = 0; x < Controls.GetLength(); x++)
if (Controls[x] is Button)
Controls[x].Enabled = false;
}
答案 1 :(得分:0)
你应该循环遍历所有按钮,然后禁用它们。
public static void disableButtons(Control parent)
{
foreach (Control c in parent.Controls)
if (c.GetType() == typeof(Button))
c.Enabled = false;
else
disableButtons(c);
}
然后在您的代码中,您应该传递面板(或表单)contatinig您的目标按钮。例如,如果您的按钮位于panel1中,那么您应该使用disableButtons(panel1);