I have a win32 window with background color blue. I have created a button on the window using the code
// code for creating button
hButton1= CreateWindow(_T("BUTTON"),_T("Test button"), BS_ICON | WS_VISIBLE | WS_CHILD ,800,200,228,228,hWnd, (HMENU)1,NULL,NULL);
I loaded a .png transparent image as button image using the code
// code to
// using GDI
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
Gdiplus::Bitmap* m_pBitmap;
HICON hicon;
m_pBitmap = Gdiplus::Bitmap::FromFile(L"d:\\gear.png");
m_pBitmap->GetHICON(&hicon);
LRESULT lr = SendMessage(hButton1,BM_SETIMAGE,IMAGE_ICON,(LPARAM)hicon );
ShowWindow(hButton1,SW_SHOW);
Now the button is displayed with transparent .png image data with button default background color. I changed the button background color to blue. But when we load .png file , then button color changed to default color.
I need to keep the transparent area of the button the same color as the background color of the window i.e. blue. You can refer the image of my window
AFAIK there is no simple way to make the background of a button transparent and let it only draw the icon.
One can use custom draw to completely control the appearance of the button. There is also "owner draw" but for buttons this technique is outdated as of Windows Vista. Custom draw has the advantage that you don't have to modify the button styles (so you can keep
BS_DEFPUSHBUTTON
, for instance) and it is also more flexible as you only need to do part of the drawing if you wish so. For our use case we need to draw everything though.To use custom draw, handle the
NM_CUSTOMDRAW
notification in the window procedure of the parent of the button. WhenNMCUSTOMDRAW::dwDrawStage
equalsCDDS_PREERASE
, do your drawing and returnCDRF_SKIPDEFAULT
so Windows doesn't paint over what you have drawn.To achieve transparency, one can call
DrawThemeParentBackground()
to draw the background of the parent window before callingDrawIconEx()
to draw the icon transparently over the background.Example
Here is a complete working example program. Error handling omitted for clarity.
This is my button image ("test.png"):
And this is how the final result looks like: