简体   繁体   中英

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. 在此处输入图像描述

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM