Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I've searched high and low, but for some reason I can't find a tutorial for loading an image (or in fact any resource) from a resx file in C++/CLI.

I have my project's soultion set up like this:

MyProject
-HeaderFiles
--Form1.h
---Form1.resx (not using this, as VS likes to automatically remove stuff from it)
-Resource Files
--Image1.png
--Image2.png
--Resources.resx

The Resources.resx file also contains the images.

Any ideas?
Posted
Updated 26-Apr-11 22:58pm
v2

Typically, after posting I found a solution myself (by searching for C++.net instead of c++/cli). For completeness it was:

C++/CLI
using namespace System;

Reflection::Assembly^ pxAssembly = Reflection::Assembly::GetExecutingAssembly();
String^ pxResName = pxAssembly->GetName()->Name + ".Resources"; //Note: add your resourcefile name here, i.e. ".MyResourceFile" as it appears in solution explorer, without it's extension
s_pxResourceManager = (gcnew Resources::ResourceManager(pxResName,pxAssembly));

pictureBox1->Image = (cli::safe_cast<Drawing::Bitmap^>(s_pxResourceManager->GetObject("my_png_image"))) //note: this is the exact name from the resx, not the filename or name in solution explorer. By default it's name in the resx won't contain it's extension.
 
Share this answer
 
v2
I tried to set the BackgroundImage property of a form with a PNG image (the PNG image was stored in the Form1.resX file), and the designer added these lines in the InitializeComponent method:

C++
void InitializeComponent(void)
{
    System::ComponentModel::ComponentResourceManager^  resources = (gcnew
        System::ComponentModel::ComponentResourceManager(Form1::typeid));
    this->SuspendLayout();
    // 
    // Form1
    // 
    ...
    this->BackgroundImage = (cli::safe_cast<system::drawing::image^>(resources->GetObject(L"$this.BackgroundImage")));
    ...
}


So I suppose you can use ComponentResourceManager class and GetObject method with the appropriate name.
 
Share this answer
 
Comments
Paul Cardy 27-Apr-11 6:53am    
Thanks. Yeah, I noticed this too, but I can't put the resource in Form1's resx as the designer automatically clears it when adding/removing it's resources and the ComponentResourceManager only seems to allow a type as a constructor (Which it then uses to make a string description), rather than me explicitly telling my resources string description. See my solution for how I eventually solved this.
Olivier Levrey 27-Apr-11 7:20am    
Ok it is good you found it by yourself.
Cheers.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900