Wednesday, July 31, 2019

Using Resources to store images in a windows forms C# program


It is useful to store the images used by a program inside the executable as resources. Visual studio offers an efficient way to do that.

The method is very simple  but I always forget how to do it. So, this is a very short tutorial.

Note: I use Visual studio 2017 but the procedure is similar with other versions.

1.    Create the project

We use Visual studio to create a windows Forms App.


2.    Put the resource in the project

Open the Resource.resx file by double clicking on it. (Visual studio will open a specific editor)



In the toolbar of this editor select Add Resource and select “Add existing file” then choose the desired image file (here I will use summer.bmp).



This will create a new resource containing the desired image



3.    Use the image

You can now use the image resource in the designer i.e. as the image property of a Picture box



But you can also access the image in the code by using <program_name>.Properties.Resources.<resourcename>.

See example below:

namespace image_in_ressource
{
    public partial class Form1 : Form
    {
        private Image summerImage;
        public Form1()
        {
            InitializeComponent();
            summerImage = new Bitmap(image_in_ressource.Properties.Resources.summer);
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawImageUnscaled(summerImage, new Point(0, 0));
        }
    }
}


1 comment:

  1. Buy a Personalized Stainless Steel Tombola Necklace by Matt Sledge
    Buy a Personalized mens titanium wedding bands Stainless 2018 ford fusion energi titanium Steel Tombola Necklace by titanium trim hair cutter Matt titanium tools Sledge (Shining). titanium exhaust tips

    ReplyDelete