从C#中的每个按钮中删除悬停样式

时间:2017-06-04 20:23:25

标签: c# winforms

我想将此代码添加到我的C#项目中的每个按钮:

button1.FlatAppearance.MouseDownBackColor = button1.BackColor;
button1.FlatAppearance.MouseOverBackColor = button1.BackColor;
button1.FlatStyle = FlatStyle.Flat;

我在Form_Load事件中尝试过此代码,但var b保持为null:

foreach (Control c in Controls)
        {
            Button b = c as Button;
            if (b != null)
            {
                b.FlatAppearance.MouseOverBackColor = b.BackColor;
                b.FlatAppearance.MouseDownBackColor = b.BackColor;
                b.FlatStyle = FlatStyle.Flat;
            }
        }

我该怎么办?

1 个答案:

答案 0 :(得分:1)

我只是假设这是关于WinForms的。

由于您的代码似乎在按钮直接位于表单上时起作用,因此它们可能位于表单上的另一个控件(容器)上。您现在可以搜索容器并检查它们是否包含按钮,但是当它们也有容器时会变得很笨拙。因此我建议使用递归:

private List<Control> GetAllControls(Control parent)
{
    List<Control> controls = new List<Control>();
    controls.AddRange(parent.Controls.Cast<Control>()); //add all controls directly being on the current control
    controls.AddRange(parent.Controls.Cast<Control>().SelectMany(GetAllControls)); //add all children from each control
    return controls;
}

你可以这样打电话:

foreach (Control c in GetAllControls(this))
{
    Button b = c as Button;
    if (b != null)
    {
        b.FlatAppearance.MouseOverBackColor = b.BackColor;
        b.FlatAppearance.MouseDownBackColor = b.BackColor;
        b.FlatStyle = FlatStyle.Flat;
    }
}

您可以阅读有关递归here的更多信息。