How to apply same style on all buttons in windows form

守給你的承諾、 提交于 2019-12-11 11:18:40

问题


i have multiple buttons in my windows form application , and i want to apply some style on btnhover like this

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

i want to put this style at one place and i want that it atuomatically apply on all buttons in my form . how can i do this , Please help me and thanks in advance


回答1:


If you really want to put this in one place and have auto-styled forms, that would be its own class:

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

Then inherit from this class instead of Form.




回答2:


This won't automatically apply it to new buttons that are added to the form, but it will apply it to all existing buttons as I suspect is what you really want to do:

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

Note you will have to change your event handlers to use sender instead of directly using button1, like:

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


来源:https://stackoverflow.com/questions/13090639/how-to-apply-same-style-on-all-buttons-in-windows-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!