[英]How to change colour of button whenever it is pressed?
To make sure that the player knows what difficulty they have chosen to proceed with onto my game, I want the current difficulty to be clearly indicated by the button's forecolour. 为了确保玩家知道他们选择继续前进到我的游戏上的难度,我希望通过按钮的前景色清楚地表明当前的难度。 Here's my code thus far that just changes the forecolour of each button whenever they're pressed:
到目前为止,这是我的代码,只要按下每个按钮,它们就会改变其前景色:
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();
}
}
But I had difficulty making sure that when the player decides to choose another option, the other 2 have the black forecolour property. 但是我很难确保当玩家决定选择另一个选项时,其他两个选项具有黑色前景色属性。 I used this beforehand but it brought about issues like the fact that whenever I pressed a button, the Medium and Hard buttons decided to change their forecolour to white:
我事先使用过此方法,但是它带来了这样的问题,例如,每当我按下按钮时,中按钮和硬按钮都会决定将其前景色更改为白色:
if (difficulty == "Hard" || difficulty = "Medium")
{
this.ForeColour = Color.Black;
}
How can I go about creating a loop that would change each button's forecolour depending on the user's choice of button? 如何创建一个循环,该循环将根据用户对按钮的选择来更改每个按钮的前景色?
Easiest might be just to create a toggle function eg 最简单的方法可能只是创建一个切换功能,例如
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;
}
}
and then on every click event you just call this function with the appropriate 'button number' 然后在每次点击事件中,您只需使用相应的“按钮号”调用此函数
eg 例如
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);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.