Search code examples
wpfc++-cliembedded-resource

Embedded image resource in hosted WPF control


My setup is kinda unorthodox - The CLR is hosted in a native Win32 application. Application loads and invokes a managed assembly (written in C++/CLI). Assembly creates a Windows Forms form with a WPF ElementHost. ElementHost gets populated with a stack panel that includes an image control and label control.

The managed assembly contains embedded image resources. The name of the resource file (in the project) is 'Images' and that of the particular resource in question is 'ISIconDB'.

How do I use the aforementioned resource as the image control's source?


Solution

  • Figured it out.

    [DllImport("gdi32.dll")] int DeleteObject(IntPtr hObject);
    
    //Drawing::Bitmap^ OrgResource; 
    
    Windows::Media::Imaging::BitmapSource^ Marshalled = nullptr;
    
    try {
    Marshalled = System::Windows::Interop::Imaging::CreateBitmapSourceFromHBitmap(OrgResource->GetHbitmap(),
    IntPtr::Zero, Windows::Int32Rect::Empty, Windows::Media::Imaging::BitmapSizeOptions::FromEmptyOptions()); 
    }
    catch (...) { 
    Marshalled = nullptr;
    } 
    finally { 
    DeleteObject(OrgResource->GetHbitmap());
    }