如何在按下按钮时更改按钮的背景色,以及如何使用另一个按钮将颜色更改为另一种颜色

时间:2020-03-05 12:24:30

标签: c# winforms

我一直在使用Windows的电影院预订软件,它有大约20个按钮,我无法使用我的按钮代码来工作,它只能变成(GREEN),按下后没有任何功能可以将其更改为按下预订按钮后为红色。

private Button lastButton = null;

private void button57_Click(object sender, EventArgs e)
{
    // Change the background color of the button that was clicked
    Button current = (Button)sender;
    current.BackColor = Color.GreenYellow;

    // Revert the background color of the previously-colored button, if any
    if (lastButton != null)
        lastButton.BackColor = SystemColors.Control;

    // Update the previously-colored button
    lastButton = current;
}

1 个答案:

答案 0 :(得分:0)

当您连续两次按下同一按钮时,会出现问题,因为上一个和当前按钮是相同的。我会排除这种情况:

if (lastButton != null && lastButton != current) {
    lastButton.BackColor = SystemColors.Control;

    // Update the previously-colored button
    lastButton = current;
}