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

时间:2012-10-26 16:16:47

标签: 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) {
  button1.UseVisualStyleBackColor = true;
}

我想将这种风格放在一个地方,我希望它能够自动应用于我表单中的所有按钮。我怎么能这样做,请帮助我,并提前感谢

2 个答案:

答案 0 :(得分:1)

如果你真的想把它放在一个地方并且有自动样式的形式,那就是它自己的类:

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

然后从此类继承而不是Form

答案 1 :(得分:0)

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

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

请注意,您必须更改事件处理程序才能使用sender而不是直接使用button1,例如:

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

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