Winforms 如何在windows窗体中的所有按钮上应用相同的样式

Winforms 如何在windows窗体中的所有按钮上应用相同的样式,winforms,windows-forms-designer,Winforms,Windows Forms Designer,我的windows窗体应用程序中有多个按钮,我想像这样在btnhover上应用一些样式 private void button1_MouseEnter(object sender, EventArgs e) { button1.UseVisualStyleBackColor = false; button1.BackColor = Color.GhostWhite; } private void button1_MouseLeave(object sender, EventArgs e)

我的windows窗体应用程序中有多个按钮,我想像这样在
btnhover
上应用一些样式

private void button1_MouseEnter(object sender, EventArgs e) {
  button1.UseVisualStyleBackColor = false;
  button1.BackColor = Color.GhostWhite;
}
private void button1_MouseLeave(object sender, EventArgs e) {
  button1.UseVisualStyleBackColor = true;
}
我想把这个样式放在一个地方,我想它自动应用到我表单中的所有按钮上。如何做到这一点,请帮助我并提前感谢

这不会自动将其应用于添加到表单中的新按钮,但会将其应用于所有现有按钮,因为我怀疑这是您真正想要做的:

partial class MyForm
{
    foreach(var b in this.Controls.OfType<Button>())
    {
        b.MouseEnter += button1_MouseEnter;
        b.MouseLeave += button1_MouseLeave;
    }
}

如果您真的想把它放在一个地方,并拥有自动样式化的表单,那将是它自己的类:

class ButtonStyledForm : Form
{
    protected override void OnControlAdded(ControlEventArgs e)
    {
        base.OnControlAdded(e);

        if (e.Control.GetType() == typeof(Button))
        {
            e.Control.MouseEnter += button_MouseEnter;
            e.Control.MouseLeave += button_MouseLeave;
        }
    }    

    protected override void OnControlRemoved(ControlEventArgs e)
    {
        base.OnControlRemoved(e);

        if (e.Control.GetType() == typeof(Button))
        {
            e.Control.MouseEnter -= button_MouseEnter;
            e.Control.MouseLeave -= button_MouseLeave;
        }
    }

    private void button_MouseEnter(object sender, EventArgs e) {
        var c = (Button)sender;
        c.UseVisualStyleBackColor = false;
        c.BackColor = Color.GhostWhite;
    }

    private void button_MouseLeave(object sender, EventArgs e) {
        var c = (Button)sender;
        c.UseVisualStyleBackColor = true;
    }
}
然后从该类继承,而不是从
表单
继承

class ButtonStyledForm : Form
{
    protected override void OnControlAdded(ControlEventArgs e)
    {
        base.OnControlAdded(e);

        if (e.Control.GetType() == typeof(Button))
        {
            e.Control.MouseEnter += button_MouseEnter;
            e.Control.MouseLeave += button_MouseLeave;
        }
    }    

    protected override void OnControlRemoved(ControlEventArgs e)
    {
        base.OnControlRemoved(e);

        if (e.Control.GetType() == typeof(Button))
        {
            e.Control.MouseEnter -= button_MouseEnter;
            e.Control.MouseLeave -= button_MouseLeave;
        }
    }

    private void button_MouseEnter(object sender, EventArgs e) {
        var c = (Button)sender;
        c.UseVisualStyleBackColor = false;
        c.BackColor = Color.GhostWhite;
    }

    private void button_MouseLeave(object sender, EventArgs e) {
        var c = (Button)sender;
        c.UseVisualStyleBackColor = true;
    }
}