Resources, where to put them, and how to reference them in C#

后端 未结 4 1409
日久生厌
日久生厌 2020-12-15 07:49

I\'ve worked with C# and other programming languages for a while now, and am ashamed to say I\'m unfamiliar with the standard on where to put resources such as program icons

4条回答
  •  一个人的身影
    2020-12-15 08:42

    For completion I wanted to expound on some of the answers listed.

    Embed in Resources.resx

    Resources.resx should have been created when your WinForms project was created. You can view it under Properties in the Solution Explorer.

    enter image description here

    Double click Resources.resx to open the designer. You can copy from Windows Explorer and paste in the VS resources designer. This tool is smart enough to figure out what type of resource it is, and you can see in the screen shot below that similar resource types are grouped together under the menu bar's drop down list.

    enter image description here

    From this point you can follow the accepted answer and manually assign the resource to a control's property...

    this.BackgroundImage = Properties.Resources.MyImage;


    Embed in form via designer

    Using the designer, you can embed a resource in a form's .resx. Select the control in the designer and open the Properties window (F4 is default shortcut key). Find the appropraite property, such as Icon for a form. Click the ellipses button to bring up the Open File dialog. Browse to the resource (if you embedded it in the Resources.resx it will actually be in the Resources folder - which would have been created when you added your first resource to Resources.resx - and you should use the first method above), and select the correct resource.

    In the image below you can see the "scrape.ico" file being set as the Main form's Icon.

    enter image description here

    This example would end up generating a line in the Main form's designer like this...

    this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
    

    where...

    System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main));
    

    and in main.resx...

    
        
            ...img data...
        
    
    

提交回复
热议问题