2

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

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

4

2 回答 2

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.

于 2012-10-26T16:27:30.087 回答
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;
}
于 2012-10-26T16:22:15.553 回答