GDI + Graphics :: DrawImage not working

I am trying to make an image using GDI +. When I do this inside WM_PAINT , it works:

 case WM_PAINT: { hdc = BeginPaint(hWnd, &ps); Gdiplus::Graphics graphics(hdc); Gdiplus::Image gdiImage(L"unt.png"); graphics.DrawImage(&gdiImage, 40, 40); EndPaint(hWnd, &ps); break; } 

But when I do this by pressing a button or inside WM_CREATE , it does not draw an image:

 HDC hdc2 = GetDC(hWnd); Gdiplus::Graphics graphics(hdc2); Gdiplus::Image gdiImage(L"unt.png"); graphics.DrawImage(&gdiImage, 40, 40); 

Even if I use BeginPaint() and EndPaint() , it still fails. So, is there a way to draw an image outside of WM_PAINT ?

+5
source share
2 answers

In Win32, almost all drawings must be executed in the WM_PAINT handler. You probably do not see any picture, because as soon as you finish processing the button click, you will get WM_PAINT.

If you paint outside of WM_PAINT, your drawing has a short lifespan due to the windows being invalidated, and then the WM_PAINT message.

Thus, the correct way to draw in Win32 is with the WM_PAINT handler.

I edited the answer after the comment of the author. Suppose you need to change the image after a mouse click. You can do:

 case WM_PAINT: { hdc = BeginPaint(hWnd, &ps); Gdiplus::Graphics graphics(hdc); Gdiplus::Image gdiImage(clicked ? L"image_A.png" : L"image_B.png"); graphics.DrawImage(&gdiImage, 40, 40); EndPaint(hWnd, &ps); break; } case WM_LBUTTONDOWN: { clicked = true; InvalidateRect(hwnd, NULL, true); break; } 

The InvalidateRect function is the answer. With this function, you tell Windows to redraw the window. This is a link to the man page: InvalidateRect

+4
source

If you need to update the image based on the click of a button (or any other Windows event handler, for that matter), you should invalidate the area occupied by the image on the screen, usually through InvalidateRect() , and then your WM_PAINT handler draws the image.

+1
source

Source: https://habr.com/ru/post/1245346/


All Articles