What is the simplest way to display (and change) an image resource on a WPF dialog (using C++/CLI)?

好久不见. 提交于 2019-12-01 13:41:16

Well it may not be the best solution, but the following works.

Create a new Windows Forms Application

Add these libraries to your linker settings (Project Proerties -> Link -> Input -> Additional Dependencies):

User32.lib Gdi32.lib

Add these headers:

#include <windows.h>
#include "resource.h"

Add these namespaces:

using namespace System::Reflection;
using namespace System::Runtime::InteropServices;

Add a pair of bitmaps to your resources and call them IDB_BITMAP1 and IDB_BITMAP2.

Add a picture box called m_pictureBox1.

Add a button and double-click the button to add an on-click handler:

System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
{
    // Remove any previously stored images
    if(m_pictureBox1->Image != nullptr)
    {
        delete m_pictureBox1->Image;
    }

    // Pick a new bitmap
    static int resource = IDB_BITMAP1;
    if( resource == IDB_BITMAP2)
    {
        resource = IDB_BITMAP1;
    }
    else
    {
        resource = IDB_BITMAP2;
    }

    // Get the primary module
    Module^ mod = Assembly::GetExecutingAssembly()->GetModules()[0];

    // Get the instance handle 
    IntPtr hinst = Marshal::GetHINSTANCE(mod);

    // Get the bitmap as unmanaged
    HANDLE hbi = LoadImage((HINSTANCE) hinst.ToPointer(),MAKEINTRESOURCE(resource),IMAGE_BITMAP,0,0,LR_DEFAULTCOLOR); 

    // import the unmanaged bitmap into the managed side 
    Bitmap^ bi = Bitmap::FromHbitmap(IntPtr(hbi));

    // insert the bitmap into the picture box
    m_pictureBox1->Image = bi;

    // Free up the unmanaged bitmap
    DeleteObject(hbi);

    // Free up the instance and module
    delete hinst;
    delete mod;
}

..et voila the bitmaps are stored neatly in you app and each time you click the button the images will swap.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!