Search code examples
c++bitmapmfcpicturebox

Set bitmap into CStatic object


I'm trying to add one bitmap into a picture box. This is what I've tried:

void DlgError::Define_Image()
{
    // I generate all requiered elements.
    CBitmap bitmap;

    // Depending on the type of the message, I define the image to show.
    switch (Message_Type)
    {
        case Error: bitmap.LoadBitmap(IDB_ERROR); break;
        case Warning: break;

        case Information:
        default: bitmap.LoadBitmap(IDB_INFORMATION); break;
    }

    // I set the new picture.
    m_picture.ModifyStyle(0, SS_BITMAP);
    m_picture.SetBitmap(bitmap);
}

I don't know why it's not working. I have the same code I've in some forums. Can anybody help me? I have to define some extra styles?

The picture box has Bitmap as its type (Can be hanged in Picture control properties)

SOLUTION

I must say that the solution is a combination of both answers. Finally, I define one local variable and I use the next code in order to do what I want.

void DlgError::Define_Image()
{
    // Depending on the type of the message, I define the image to show.
    switch (Message_Type)
    {
        case Error: bitmap.LoadBitmap(IDB_ERROR); break;
        case Warning: break;

        case Information:
        default: bitmap.LoadBitmap(IDB_INFORMATION); break;
    }

    // I set the new picture.
    m_picture.ModifyStyle(SS_ENHMETAFILE, SS_BITMAP);
    m_picture.SetBitmap(bitmap);
}

Thanks everyone who helped me!


Solution

  • You are using the CBitmap object as a local variable in the Define_Image function. Once the function goes out of scope, the bitmap is destroyed by the destructor of CBitmap object (there are no ref-counts here).

    You need to detach the object and then pass the HBITMAP handle to SetBitmap of CStatic.

    Fortunatly, only a single line is required:

     m_picture.SetBitmap((HBITMAP)bitmap.Detach());