tags:

views:

768

answers:

3

Hi!,

Is there any way to set the same icon to all my forms without having to change one by one? Something like when you setup GlobalAssemblyInfo for all your projects inside your solution.

Thanks for your time.

+9  A: 

One option would be to inherit from a common base-Form that sets the Icon in the constructor (presumably from a resx). Another option might be PostSharp - it seems like it should be possible to do this (set .Icon) via AOP; not trivial, though. Finally, you could use a simple utility method (perhaps an extension method) to do the same.

Best of all, with the first option, you could probably risk a [Ctrl]+H (replace all) from ": Form" or ": System.Windows.Forms.Form" to ": MyCustomForm"

Marc Gravell
that's the answer right there
sebastian
I think option #1 (derive from a common form with it in the constructor) is the clear winner here.
John Rudy
I still can't believe that inheritance never came to my mind .. thanks for your fast (really fast) answer!!!!
Matías
+3  A: 

In additional to Marc's recommendation, you may want your forms to automatically inherit the icon of the executing assembly that contains/calls them.
This can be done by adding the following code to your inherited form:

public MyCustomForm()
{
    Icon = GetExecutableIcon();
}

public Icon GetExecutableIcon()
{
    IntPtr large;
    IntPtr small;
    ExtractIconEx(Application.ExecutablePath, 0, out large, out small, 1);
    return Icon.FromHandle(small);
}

[DllImport("Shell32")]
public static extern int ExtractIconEx(
    string sFile,
    int iIndex,
    out IntPtr piLargeVersion,
    out IntPtr piSmallVersion,
    int amountIcons);
Nathan Baulch
A: 

I'm not sure if the MS VS designer can deal with Forms that don't derive directly from Form. If not then you may try to copy the main form's icon to all other forms: for each form in Forms collection form.icon = MainFrom.Icon

Or perhaps in each Form's _Loaded event: Icon = MainFrom.Icon

GregUzelac
omg - don't do this! VS form designer works fine with inherited forms!
TheSoftwareJedi