I want to have both an image icon and text on the same button, like here in Word for example.
I set an icon on a button, but the text disappears.
Instructions on how to get a button to display both an image and text are outlined in the Button Styles reference1:
The appearance of text or an icon or both on a button control depends on the BS_ICON and BS_BITMAP styles, and whether the BM_SETIMAGE message is sent. The possible results are as follows.
BS_ICON or BS_BITMAP set? | BM_SETIMAGE called? | Result --------------------------+---------------------+-------------------- Yes | Yes | Show icon only. No | Yes | Show icon and text. Yes | No | Show text only. No | No | Show text only
In other words: Don't set the BS_ICON
or BS_BITMAP
style (but do set the BS_TEXT
style), and send a BM_SETIMAGE
message once the button has been created.
To see this in action, create a standard Windows Desktop application in Visual Studio, and apply the following changes:
Enable visual styles. This is easiest done by placing a #pragma
linker directive into the only compilation unit:
#pragma comment(linker,"\"/manifestdependency:type='win32' \
name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \
processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
Create the button in the main window's WM_CREATE
handler:
case WM_CREATE:
{
HWND btn{ ::CreateWindowExW(0x0, L"BUTTON", L"Button text",
WS_VISIBLE | WS_CHILD | BS_TEXT,
10, 10, 200, 50, hWnd, (HMENU)110,
nullptr, nullptr) };
HICON icon{ (HICON)::LoadImageW(::GetModuleHandle(nullptr),
MAKEINTRESOURCEW(107),
IMAGE_ICON, 32, 32, 0x0) };
::SendMessageW(btn, BM_SETIMAGE, IMAGE_ICON, (LPARAM)icon);
}
break;
Make sure to adjust the numeric constants as needed. 110
is the button's control identifier, 107
is the resource ID of the wizard-generated application icon resource, and 32
are the width and height of the requested icon.
This code produces the following output:
1 Note, that you have to enable visual styles for this to work.