Optimus1
Optimus1

Reputation: 448

How to draw on standart button WinApi

I want to draw a simple square on a button.

I created a regular window and a regular button in it. Now, in the window procedure of my window, in the WM_PAINT message, I get the HDC of my button and draw a square:

LRESULT CALLBACK WndProc(HWND   hWnd, UINT   message, WPARAM wParam, LPARAM lParam)
{

    if (message == WM_PAINT)
    {
        PAINTSTRUCT ps;
        HDC my_hdc = BeginPaint(hWnd, &ps);


        //---------------------------------------------
        HDC my_button_HDC = GetDC(GetDlgItem(hWnd, 11));  //Get HDC my button

        Rectangle(my_button_HDC, 5, 5, 30, 30);
        //---------------------------------------------


        EndPaint(hWnd, &ps);
}


WinMain()
{
//standart code create window and button...
}

When creating a window, a square does not appear on the button. It appears ONLY when I move my window down outside of the screen and lift it up. enter image description here

But, as soon as I resize the window or click on the button, the square disappears again.

I don't understand why this is happening.

Upvotes: 0

Views: 858

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597550

You are drawing on the button only when its parent window is being painted (also, you are leaking the button's HDC). Resizing the window does not always trigger a repaint.

But even when it does, when the button itself paints itself, it will draw over anything you have already drawn.

The correct way to draw on a standard Win32 button is to either:

  • give the button the BS_OWNERDRAW style, and then have its parent window handle the WM_DRAWITEM message.

  • if ComCtl32.dll v6 is being used (see Enabling Visual Styles), the parent window can instead handle the NM_CUSTOMDRAW message, BS_OWNERDRAW is not needed. See Custom Draw for more details.

Upvotes: 1

Related Questions