CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Adding Icon / Image to a CButton object (VC++ / MFC / Win32)

Sometimes it is required to set an Image (or) Icon to a CButton MFC object for better User Interface display. The following steps cover how to add an Icon/Image to a CButton Object.

Assume the following:

  • CTestDialog – is the test dialog class that is derived from the MFC class CDialog.
  • IDC_BUTTON_ICON – is the button on the dialog.
  • IDC_BUTTON_IMAGE – is the button on the dialog.
  • IDI_ICON1 – is the 16×16 icon resource.
  • IDB_BITMAP1 – is the 16×16 bitmap resource.

Step (1): We have a dialog resource and two buttons on the dialog. One is IDC_BUTTON_ICON & IDC_BUTTON_IMAGE. We will place an icon on the button with ID IDC_BUTTON_ICON & an image on the button with ID IDC_BUTTON_IMAGE.

Step (2): Select the button IDC_BUTTON_ICON and set its property “Icon” to True in the resource editor. And the same way, select the button IDC_BUTTON_IMAGE and set its “Bitmap” property to True. Note that “Icon” and “Bitmap” properties are mutually exclusive; which means, if you set Bitmap property to True, Icon property will automatically become to False for that button.

Step (3): Now we need to place an icon/image on the buttons. We need icon & image resources to be defined in the application resource. We have the IDI_ICON1 icon and IDB_BITMAP1 bitmap resource already defined for this purpose. So, we need to map these to buttons.

Step (4): We need to write a code that maps the icon/image to the buttons. This code needs to be placed in the OnInitDialog() function of the dialog class CTestDialog. See the following code snippet.

BOOL CTestDialog::OnInitDialog()
{
...
// -- Get CButton pointer of IDC_BUTTON_ICON button
CButton *pButton = (CButton *)GetDlgItem(IDC_BUTTON_ICON);
if ( pButton && pButton->GetSafeHwnd() )
{
pButton->SetIcon((HICON)LoadImage(AfxGetApp()->m_hInstance,
MAKEINTRESOURCE(IDI_ICON1),
IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR));
}
// -- Get CButton pointer of IDC_BUTTON_IMAGE button
pButton = (CButton *)GetDlgItem(IDC_BUTTON_IMAGE);
if ( pButton && pButton->GetSafeHwnd() )
{
pButton->SetBitmap((HBITMAP)LoadImage(AfxGetApp()->m_hInstance,
MAKEINTRESOURCE(IDB_BITMAP1),
IMAGE_BITMAP, 16, 16, LR_COLOR));
}
...
}

Step (5): Once you run your dialog application, you will see the icon/image on the buttons.

by Code Steps

Adding Icon / Image to a CButton object (VC++ / MFC / Win32)

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top