Change Default Winform Icon Across Entire App

后端 未结 5 560
甜味超标
甜味超标 2020-12-17 16:32

Can I change the default icon used on a Winform?

Most of my forms have their icon property set to a custom icon. For the few forms that slip through the cracks, I d

5条回答
  •  甜味超标
    2020-12-17 17:20

    The default icon is embedded in the winforms dll - looking at reflector (DefaultIcon) it is:

    defaultIcon = new Icon(typeof(Form), "wfc.ico");
    

    There is no magic in there that checks another common location, so you can't do it without changing code.

    You could always embrace the forces of darkness with field-based reflection? Note: this is hacky and brittle. On your own head! But it works:

    [STAThread]
    static void Main() {
        // pure evil
        typeof(Form).GetField("defaultIcon",
                BindingFlags.NonPublic | BindingFlags.Static)
            .SetValue(null, SystemIcons.Shield);
    
        // all forms now default to a shield
        using (Form form = new Form()) {
            Application.Run(form);
        }
    }
    

    To do it properly; two common options;

    • a base Form class which has the icon set
    • a factory Form method - perhaps something like:

    code:

    public static T CreateForm() where T : Form, new() {
        T frm = new T();
        frm.Icon = ...
        // any other common code
        return frm;
    }
    

    Then instead of:

    using(var frm = new MySpecificForm()) {
        // common init code
    }
    

    Something like:

    using(var frm = Utils.CreateForm()) {
    
    }
    

    Of course - that isn't much prettier! Another option might be a C# 3.0 extension method, perhaps as a fluent API:

    public static T CommonInit(this T form) where T : Form {
        if(form != null) {
            form.Icon = ...
            //etc
        }
        return form;
    }
    

    and

    using(var frm = new MySpecificForm().CommonInit()) {
        // ready to use
    }
    

    This is then just a .CommonInit() away from your existing code.

提交回复
热议问题