Reusing icons in a winforms app using eco service mechanism
Windows.Forms may not be the hottest technology these days, but it’s a convenient platform to write to.
I’m currently writing an app for a friend using good ol’ windows forms. There’s one “main form” and then several forms for data entry, searching, data maintenance and so on. All, or at least most, of these forms have the same icon. For one thing – what if the icon I selected isn’t what my customer expected? Another thing is the resources used to store multiple copies of the icon. Not a whole lot, but still.
What I would want to do is set the icon on the main form and have all the other forms pick it up. Now, there is no concept of main form, though one could probably make a reasonable guess from Application.OpenForms. However, I deceided not to investigate that avenue further, and instead define a service like
-
-
public interface IIconService
-
{
-
void RegisterIcon(Form f);
-
void SetIcon(Form f);
-
}
I implemented that in a very simple way as
-
-
public class IconService : IIconService
-
{
-
private Icon icon;
-
public void RegisterIcon(Form f)
-
{
-
icon = f.Icon;
-
}
-
-
public void SetIcon(Form f)
-
{
-
f.Icon = icon;
-
}
-
}
Using the service mechanisms available in Enterprise Core Objects (ECO) it’s possible to install the service
-
-
public EcoProject1EcoSpace(): base()
-
{
-
InitializeComponent();
-
this.RegisterEcoService(typeof(IIconService), new IconService());
-
}
and make ita property of the ecospace
-
-
public IIconService IconService { get { return GetEcoService<IIconService>(); } }
In the constructor of the main form, register the main form’s icon.
-
-
public MainForm(EcoProject1.EcoProject1EcoSpace ecoSpace)
-
{
-
InitializeComponent();
-
rhRoot.EcoSpace = ecoSpace;
-
ecoSpace.IconService.RegisterIcon(this);
-
}
In the constructor of the other forms, set the icon.
-
-
private frmSearchPersons(EcoProject1.EcoProject1EcoSpace ecoSpace)
-
{
-
InitializeComponent();
-
rhRoot.EcoSpace = ecoSpace;
-
ecoSpace.IconService.SetIcon(this);
-
}
Now, when changing the icon of the main form, it will ripple through to all the other forms, and we’ve shaved off a kB for each form in the application using the same icon.
–Jesper Hogstrom