Why GetDC function does not works?

I am creating a game with the Win32 API and tried to draw a button by myself with this following code:

HWND button = CreateWindow("BUTTON", "", WS_CHILD | WS_VISIBLE | BS_OWNERDRAW, 100, 100, 250, 40, hwnd, NULL, instance, NULL);
HDC dc = GetWindowDC(button);
TextOut(dc, 10, 10, "test", 5);
ReleaseDC(button, dc);

I want to clarify for everyone that I have tried for many situations and various functions, like FillRect, MoveTo, DrawText ... The point is it works in WM_CTLCOLORBTN, where I get the HDC of the button with wParam. I don't understand why it doesn't work. Maybe the GetDC function is buggy? Which function should I use? I specify that I tried with other functions like GetDC or BeginPaint/EndPaint. What I need to do??


Solution 1:

When using the BS_OWNERDRAW style, you need to handle (and perform drawing in) the WM_DRAWITEM message in the parent window's windproc. This is explicitly stated in the Button Styles documentation:

BS_OWNERDRAW
Creates an owner-drawn button. The owner window receives a WM_DRAWITEM message when a visual aspect of the button has changed. Do not combine the BS_OWNERDRAW style with any other button styles.

The lParam of the WM_DRAWITEM message is a pointer to a DRAWITEMSTRUCT struct, which contains the HDC you must use for drawing, among other things.

hDC
A handle to a device context; this device context must be used when performing drawing operations on the control.