winforms 如何在c# winform中将鼠标悬停在按钮数组中的某个按钮上时更改其颜色

nwlqm0z1  于 2022-11-16  发布在  C#
关注(0)|答案(1)|浏览(256)

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

t2a7ltrp

t2a7ltrp1#

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

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;
    }
}

相关问题