Reputation: 12131
If I have a form Frm1.cs that is using some icons, images or other resources, these resources get stored in the form's resx file (Frm1.resx).
My simple question is how do I access these resources from code?
As a workaround I can store these resources in the Project resource file and they will be available via Properties.Resources.resourcename
.
However, similar syntax does not work for the resources stored in the form's resource file.
While searching for a solution I have come across several references to ResourceManager class but was not able to find a way to use that to access the form's resources...
Upvotes: 20
Views: 36804
Reputation: 2989
Building on Harold Coppoolse's answer, Visual Studio (speaking from 2022 Community) has some nice automation when it comes to accessing any given Form's resources.
With every Form created in Visual Studio, there should be an associated .resx
generated along with it (if an item with a Text
property is inserted, for example.) When you open the .resx
file in the Designer tool, there's an Access Modifier: option. Change it to the most restrictive permission possible in your language (there should be no reason to use Public
), and this will generate a FormName
.Designer.code extension file underneath the .resx
file.
In the background, Visual Studio is using ResGen.exe
to generate the strongly-typed resource class to accompany the .resx
file. What this does is create a class in the namespace specified by the Custom Tool Namespace
.resx
file property, with:
A parameterless constructor, which can be used to instantiate the strongly typed resource class.
A static (C#) or Shared (Visual Basic) and read-only ResourceManager property, which returns the ResourceManager instance that manages the strongly typed resource.
A static Culture property, which allows you to set the culture used for resource retrieval. By default, its value is null, which means that the current UI culture is used.
One static (C#) or Shared (Visual Basic) and read-only property for each resource in the .resources file. The name of the property is the name of the resource.-
This means that, in code, you simply use *Namespace*
.*FormClassName*
.*ResourceName*
to access any resource you need. No extra code is required on your part.
Upvotes: 1
Reputation: 30512
If you use visual studio designer to add resources, you get a class Resources
with static properties to access them.
To access:
this.pictureBox1.Image = Properties.Resources.MyResourceImage;
Upvotes: 1
Reputation: 464
The way to access local form resources is through an instance of ResourceManager. Suppose you got two PictureBox in a Form called Frm1:
var resources = new ResourceManager(typeof(Frm1));
var image = (Bitmap)resources.GetObject("pictureBox1.Image");
pictureBox2.Image = image;
Hope this could help you...
Upvotes: 20