按下时如何更改按钮的颜色?

时间:2018-01-06 11:56:35

标签: c# winforms

为了确保玩家知道他们选择进入我的游戏的难度,我希望当前的难度可以通过按钮的前部颜色清楚地显示出来。到目前为止,这是我的代码,只需按下每个按钮的前部颜色即可:

CustomReport

但我很难确定当玩家决定选择另一个选项时,另外两个选择具有黑色前色属性。我事先用过这个,但它带来的问题就像每当我按下按钮时,中等和硬按钮决定将它们的前色变为白色:

public Form1()
    {
        InitializeComponent();
        MinimizeBox = false;
        MaximizeBox = false;

    }

    bool diffchosen = false;
    public static string difficulty;
    public static double multiplier;
    public static int lives;

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void easyButton_Click(object sender, EventArgs e)
    {
        this.ForeColor = Color.White;


        diffchosen = true;
        difficulty = "Easy";
        multiplier = 0.8;
        lives = 4;

    }

    private void mediumButton_Click(object sender, EventArgs e)
    {
        this.ForeColor = Color.White;


        diffchosen = true;
        difficulty = "Medium";
        multiplier = 1.0;
        lives = 3;


    }

    private void hardButton_Click(object sender, EventArgs e)
    {
        this.ForeColor = Color.White;

        diffchosen = true;
        difficulty = "Hard";
        multiplier = 1.5;
        lives = 2;


    }

    private void playButton_Click(object sender, EventArgs e)
    {
        if (diffchosen == false)
        {
            MessageBox.Show("Please choose a difficulty before proceeding");
        }
        else
        {
            Game_Screen game_Screen = new Game_Screen();

            this.Hide();
            game_Screen.Show();
        }
    }

如何根据用户选择的按钮创建一个可以改变每个按钮前色的循环?

1 个答案:

答案 0 :(得分:2)

最简单的可能只是创建一个切换功能,例如。

private void ToggleButton(int button)
{
    easyButton.ForeColor = Color.Black;
    mediumButton.ForeColor = Color.Black;
    hardButton.ForeColor = Color.Black;

    switch (button)
    {
        case 1: easyButton.ForeColor = Color.White; break;
        case 2: mediumButton.ForeColor = Color.White; break;
        case 3: hardButton.ForeColor = Color.White; break;
    }
}

然后在每次点击活动中,您只需使用相应的“按钮编号”

调用此功能

e.g。

private void easyButton_Click(object sender, EventArgs e)
{
    ToggleButton(1);
    ...
}

private void mediumButton_Click(object sender, EventArgs e)
{
    ToggleButton(2);
    ...
}

private void hardButton_Click(object sender, EventArgs e)
{
    ToggleButton(3);
    ...
}