bitmap button in dialog box

Q1. m_okz is a CEdit object(control) created thru class wizard.
The following is the code in->
 BOOL CVcb1Dlg::OnInitDialog()
CBitmap b1;
       MessageBox("success","very good",MB_OK);
      HBITMAP hb=(HBITMAP)b1;
      SendDlgItemMessage (IDOK,BM_SETIMAGE,IMAGE_BITMAP,(LONG)hb);
I want to create a bitmap button on my dialog box.Both setbitmap as well as dlgitemmessage is not working.Please help me add a bitmap button.I have set the style of the button to bitmap in the dialog editor.
Who is Participating?
naveenkohliConnect With a Mentor Commented:
The problem with this code is that you have definded b1 as local variable (on stack). You need to define this as member variable so that its life is controlled by dialog box. Whats happeneing is that becaus eof local variable, your bitmap is going out of scope.

You can make use of HBITMAP operator in CBitmap to cast it to HBITMAP.

Feel free to ask more questions on this ..

Simply pass b1 to the SetBitmap function. You cannot simply typecast a CBitmap to a HBITMAP. You have to call the GetSafeHandle member.
Make sure that you have set the style of this button as Bitmap in the resource editor.

chengez_khanAuthor Commented:
naveen, thanks a lot but could you please be slightly more elaborate about the stack portion.I mean even if it is a member of the class will it not still be a local variable and hence the problem would remain the same?
P.S:Mujhe khushi hoti hai ki mere jaisa aur bhe hindustani experts excahnge mein hai aur bahut se computer me aap ke jaisa uttam hai.
Hi Changez,
Making the CBitmap variable as class memeber does not make it local. Then it life time is controlled by life of dialog box. As long as dialog box objec tis there, bitmap object will also be there. The problem you are having is that you defined your CBitmap object as local variable in function and that gets destroyed once the function goes out of scope.

You need to do some thing like this ...

class CMyDialog:: public CDialog {
CBitmap m_MyBitmap;
CButton m_BitmapButton;

CMyDialog::OnInitDialog ()
CDialog::OnInitDialog ();
m_MyBitmap.LoadBitmap (IDB_MYBITMAP);
m_BitmapButton.SetBitmap ((HBITMAP)m_MyBitmap);

or other option you can try is ..

BitmapButton.SetBitmap( ::LoadBitmap(NULL, MAKEINTRESOURCE(IDB_MYBITMAP)) );

Good Luck!
All Courses

From novice to tech pro — start learning today.