I have a Win32 program in which I have a vector which contains the HWND
of some buttons which I want to custom draw. I can owner-draw them, but all I want to do is change the background color, so it seems unnecessary to do so. However, they don't seem to change as a result of being custom drawn. They look the same.
I create the buttons like this:
#define ID_BUTTON1 40000
std::vector<HWND> ButtonsVector;
for (int i = 0, i > NumButtons, i++) {
ButtonsVector.push_back(CreateWindowEx(
NULL,
L"BUTTON", // Predefined class; Unicode assumed
L"X", // Button text
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles
x, // x position
y, // y position (substitute some x and y values for these)
20, // Button width
20, // Button height
hWnd, // Parent window
(HMENU)ID_BUTTON1 + i, // Unique button ID
(HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE),
NULL));
}
I use this WM_NOTIFY
to draw them:
HBRUSH hHotBrush;
HBRUSH hDefaultBrush;
case WM_NOTIFY:
{
LPNMHDR some_item = (LPNMHDR)lParam;
if (some_item->idFrom >= ID_BUTTON1 && some_item->code == NM_CUSTOMDRAW)
{
LPNMCUSTOMDRAW item = (LPNMCUSTOMDRAW)some_item;
if (item->uItemState & CDIS_HOT) //Our mouse is over the button
{
//Select our color when the mouse hovers our button
if (hHotBrush == NULL)
hHotBrush = CreateSolidBrush(RGB(230, 0, 0));
HPEN pen = CreatePen(PS_INSIDEFRAME, 0, RGB(0, 0, 0));
HGDIOBJ old_pen = SelectObject(item->hdc, pen);
HGDIOBJ old_brush = SelectObject(item->hdc, hHotBrush);
RoundRect(item->hdc, item->rc.left, item->rc.top, item->rc.right, item->rc.bottom, 5, 5);
SelectObject(item->hdc, old_pen);
SelectObject(item->hdc, old_brush);
DeleteObject(pen);
return CDRF_DODEFAULT;
}
//Select our color when our button is doing nothing
if (hDefaultBrush == NULL)
hDefaultBrush = CreateSolidBrush(RGB(255, 0, 0));
HPEN pen = CreatePen(PS_INSIDEFRAME, 0, RGB(0, 0, 0));
HGDIOBJ old_pen = SelectObject(item->hdc, pen);
HGDIOBJ old_brush = SelectObject(item->hdc, hDefaultBrush);
RoundRect(item->hdc, item->rc.left, item->rc.top, item->rc.right, item->rc.bottom, 5, 5);
SelectObject(item->hdc, old_pen);
SelectObject(item->hdc, old_brush);
DeleteObject(pen);
return CDRF_DODEFAULT;
}
}
break;
I needed to add the following line:
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version = '6.0.0.0' processorArchitecture = '*' publicKeyToken = '6595b64144ccf1df' language = '*'\"")
This makes sure that ComCtrl32.dll version 6 is being used, allowing the custom-drawing of button controls. One thing you have to be careful of, however, is which version of Windows you are targeting for your application, as versions older than XP do not include this version of the dll.