【问题标题】:c# disable specific buttonsc#禁用特定按钮
【发布时间】:2017-10-05 05:05:30
【问题描述】:

我正在做这个项目,现在意识到我从来没有真正使用过“启用”/“禁用”功能,现在我想禁用特定按钮,而其他按钮仍然可以运行! (希望游戏结束后重启按钮仍然有效)

有人可以帮我解决这个问题吗? 提前感谢任何答案!

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
    }
}

【问题讨论】:

    标签: c# button foreach controls


    【解决方案1】:

    取决于您的布局...但是如果您要禁用的所有按钮都是相关的,则将它们放在一个面板中...并用一行

    panel1.Enabled = false; 
    

    所有按钮都将被禁用

    如果它们不相关,也许您可​​以创建一个List<Button> 并使用这样的 foreach 循环遍历它们

    foreach(Button B In MyListOfButtons)
    {
        B.Enabled=false;
    }
    

    【讨论】:

    • 感谢您的快速回答 这是一个井字游戏,有 1 个面板,包括 9 个按钮 A1 - A3 B1 - B3 和 C1 - C3 以及重新启动和退出按钮。所以它会在游戏结束时禁用所有按钮
    • 然后你可以禁用包含按钮的面板......这将禁用其中的所有按钮
    【解决方案2】:

    试试

     private void disableButtons()
        {
            for (int x = 0; x < Controls.GetLength(); x++)
                if (Controls[x] is Button)
                    Controls[x].Enabled = false;
        }
    

    【讨论】:

    • 您好,谢谢您的回答!但不幸的是它没有奏效..
    【解决方案3】:

    您应该递归地遍历所有按钮,然后禁用它们。

    public static void disableButtons(Control parent)
    {
        foreach (Control c in parent.Controls)
            if (c.GetType() == typeof(Button))
                c.Enabled = false;
            else
                disableButtons(c);
    }
    

    然后在您的代码中,您应该传递包含目标按钮的面板(或表单)。例如,如果您的按钮在 panel1 中,那么您应该使用 disableButtons(panel1);

    【讨论】:

      猜你喜欢
      • 2012-06-28
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 2022-01-15
      相关资源
      最近更新 更多