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 project
This is the way to set the same icon to all forms without having to change one by one. This is what I coded in my applications.
FormUtils.SetDefaultIcon();
Here a full example ready to use.
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Here it is.
FormUtils.SetDefaultIcon();
Application.Run(new Form());
}
}
Here is the class FormUtils:
using System.Drawing;
using System.Windows.Forms;
public static class FormUtils
{
public static void SetDefaultIcon()
{
var icon = Icon.ExtractAssociatedIcon(EntryAssemblyInfo.ExecutablePath);
typeof(Form)
.GetField("defaultIcon", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)
.SetValue(null, icon);
}
}
And here the class EntryAssemblyInfo. This is truncated for this example. It is my custom coded class taken from System.Winforms.Application.
using System.Security;
using System.Security.Permissions;
using System.Reflection;
using System.Diagnostics;
public static class EntryAssemblyInfo
{
private static string _executablePath;
public static string ExecutablePath
{
get
{
if (_executablePath == null)
{
PermissionSet permissionSets = new PermissionSet(PermissionState.None);
permissionSets.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
permissionSets.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
permissionSets.Assert();
string uriString = null;
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly == null)
uriString = Process.GetCurrentProcess().MainModule.FileName;
else
uriString = entryAssembly.CodeBase;
PermissionSet.RevertAssert();
if (string.IsNullOrWhiteSpace(uriString))
throw new Exception("Can not Get EntryAssembly or Process MainModule FileName");
else
{
var uri = new Uri(uriString);
if (uri.IsFile)
_executablePath = string.Concat(uri.LocalPath, Uri.UnescapeDataString(uri.Fragment));
else
_executablePath = uri.ToString();
}
}
return _executablePath;
}
}
}