vclc++builder-10.2-tokyo

Changing TBitBtn Glyph at runtime


I have a VCL form with a TBitBtn on it and an TImageList containing 2 bitmaps. At runtime i run the following line of code to put one of the bitmaps on my TBitBtn:

ImageList1->GetBitmap(1, BitBtn1->Glyph);

This succesfully puts the bitmap on the TBitBtn. Then later i run the following line of code to change the bitmap and nothing happens:

ImageList1->GetBitmap(0, BitBtn1->Glyph);

Both bitmaps are present in the imagelist (0 and 1). I can swap the lines of code and prove nothing wrong with the imagelist. Here is an old post where a guy seems to solve this in Delphi. I'm thinking i must need to somehow clear the Glyph first but i don't know how in C++.


Solution

  • Here's an example of one way to use it, using a temporary TBitmap to retrieve the image from the TImageList and put it into the glyph at runtime. It does so in this example on the TBitBtn->OnClick event handler.

    void __fastcall TForm1::btn1Click(TObject *Sender)
    {
        // FOdd is a bool variable defined in the form's private section.
        // It's just being used here as a toggle to flip between the images
        this->FOdd = !this->FOdd;
    
        TBitmap *bmp = new Graphics::TBitmap();
        try {
            bmp->SetSize(this->ImageList1->Width, this->ImageList1->Height);
            this->ImageList1->GetBitmap(int(FOdd), bmp);
            this->BitBtn1->Glyph->Assign(bmp);
        }
        __finally
        {
            delete bmp;
        }    
    }
    

    @relayman357 provided the proper code for the try..__finally block to make this answer more suitable.