WinForm难度选择按钮前景色切换:如何用循环实现选中高亮
Got it, let's get this sorted out! The main issues here are that your current code is modifying the form's text color instead of the button's, and we need a way to reset all other buttons when a new difficulty is selected. Using a loop to iterate over your difficulty buttons is the perfect approach here.
Step-by-Step Solution:
- Create a collection of your difficulty buttons: This lets us easily loop through all of them to update their colors.
- Write a reusable method to update button states: This method will handle setting the selected button to white and all others to black.
- Update each button's click event: Call our reusable method and set the corresponding difficulty values.
Modified Full Code:
public Form1() { InitializeComponent(); MinimizeBox = false; MaximizeBox = false; } bool diffchosen = false; public static string difficulty; public static double multiplier; public static int lives; // Create a list to hold all our difficulty buttons private List<Button> _difficultyButtons; private void Form1_Load(object sender, EventArgs e) { // Initialize the list with our three buttons _difficultyButtons = new List<Button> { easyButton, mediumButton, hardButton }; } // Reusable method to update button highlighting private void UpdateDifficultyButtonStates(Button selectedButton) { // Loop through every button in our difficulty list foreach (Button btn in _difficultyButtons) { // Set selected button to white, others to black btn.ForeColor = btn == selectedButton ? Color.White : Color.Black; } } private void easyButton_Click(object sender, EventArgs e) { UpdateDifficultyButtonStates(easyButton); diffchosen = true; difficulty = "Easy"; multiplier = 0.8; lives = 4; } private void mediumButton_Click(object sender, EventArgs e) { UpdateDifficultyButtonStates(mediumButton); diffchosen = true; difficulty = "Medium"; multiplier = 1.0; lives = 3; } private void hardButton_Click(object sender, EventArgs e) { UpdateDifficultyButtonStates(hardButton); diffchosen = true; difficulty = "Hard"; multiplier = 1.5; lives = 2; } private void playButton_Click(object sender, EventArgs e) { if (!diffchosen) { MessageBox.Show("Please choose a difficulty before proceeding"); } else { Game_Screen game_Screen = new Game_Screen(); this.Hide(); game_Screen.Show(); } }
How This Works:
- We store all three difficulty buttons in a
List<Button>so we can iterate over them in one go. - The
UpdateDifficultyButtonStatesmethod uses aforeachloop to check each button: if it's the one the user clicked, we set its text to white; every other button gets set back to black. - We call this method at the start of each button's click event, ensuring the highlighting updates correctly every time the user switches difficulty.
内容的提问来源于stack exchange,提问作者user8721727
相关产品推荐
相关产品推荐

