当我在c#winform中将鼠标悬停在按钮数组中时,如何更改按钮的颜色



我有一个按钮列表,它是一个按钮数组。请告诉我当我悬停鼠标时如何更改每个按钮阵列按钮的颜色。当我使用循环时,我曾尝试在事件按钮中使用循环,但当我将鼠标悬停在另一个按钮上时,这个按钮仍然会改变颜色,尽管我从未为它设置任何事件。

我希望这个代码示例对有帮助

public partial class Form1 : Form
{
private Button[] buttonsArray = null;

public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GetButtonsArray();
if (buttonsArray != null)
{
foreach (Button button in buttonsArray)
{
button.MouseEnter += button_MouseEnter;
button.MouseLeave += button_MouseLeave;
}
}
}
private void GetButtonsArray()
{
// This is an example to fill array of buttons. 
// You have to fill array in your way, according to your task.
foreach (Control control in this.Controls)
if (control is Button)
buttonsArray = buttonsArray.Append(control as Button);
}

private void button_MouseEnter(object sender, EventArgs e)
{
if (sender is Button)
(sender as Button).BackColor = Color.Yellow;
}
private void button_MouseLeave(object sender, EventArgs e)
{
if (sender is Button)
(sender as Button).BackColor = SystemColors.Control;
}
}
public static class Extensions
{
public static T[] Append<T>(this T[] array, T item)
{
if (array == null)
return new T[] { item };

T[] result = new T[array.Length + 1];
array.CopyTo(result, 0);
result[array.Length] = item;
return result;
}
}

最新更新