开发者

c - win32 api rectangle is not drawn if hdc passed to method

开发者 https://www.devze.com 2023-02-09 14:16 出处:网络
I have been playing with C and win32 recently and the following has me balked: case WM_PAINT: g_crntRect = (RECT*) malloc(sizeof(RECT));

I have been playing with C and win32 recently and the following has me balked:

     case WM_PAINT:
         g_crntRect = (RECT*) malloc(sizeof(RECT));
         GetWindowRect(hwnd, g_crntRect);

         hpen = CreatePen(PS_SOLID, 1, RGB(255,25,5));

         hdc = BeginPaint (hwnd, &ps) ;

         oldPen = SelectObject(hdc, hpen);
         drawRects(hwnd, hdc);
         //Rectangle(hdc, 0, 0, 840, 525);

         SelectObject(hdc,oldPen);
         DeleteObject(hpen);

         EndPaint (hwnd, &ps) ;
         return 0 ;

So, if I call my own method above for drawing rectangles, it draws nothing, however the call to draw the rectangle in the WM_PAINT that I have commented above succeeds without a problem.

Here is 开发者_开发知识库my method:

BOOL drawRects(HWND hwnd, HDC hdc)
{

char buffer[50];
BOOL res = FALSE;
RECT tempRect = {0};
char quadStr[6] = "";
int i = 0;
quadStr[i]='*';
OutputDebugString("Going to draw");
for (i = 1; i <= 4; i++)
{
    //get rect for each quadrent from the parent
    OutputDebugString("inside for");
    getRect(g_crntRect, &tempRect, i);

    OutputDebugString("got rectr");;
    res = Rectangle(hdc, tempRect.right, tempRect.top, tempRect.right, tempRect.bottom);

    if (res == FALSE)
    {
        OutputDebugString("false");;
        sprintf(buffer, "Error: %ld", GetLastError());
        OutputDebugString(buffer);
    }
    else
    {
        OutputDebugString("drew");;
    }

    quadStr[i]='*';
    printRect(quadStr, &tempRect);
}

return TRUE;

}

Looking at debug output, everything seems fine. Proper values are being passed into the Rectangle method. However, I wonder if I am not passing HDC correctly?

Any ideas?


Looks like a simple typo. In your method you have:

res = Rectangle(hdc, tempRect.right, tempRect.top, tempRect.right, tempRect.bottom);

The second parameter should be tempRect.left not tempRect.right. You're trying to draw a zero-width rectangle.


Change

BOOL drawRects(HWND hwnd, HDC* hdc)

to

BOOL drawRects(HWND hwnd, HDC hdc)

A Windows handle is actually a pointer, so there is no need to pass it by reference. But if you do, you would need to call your function as drawRects(hwnd, &hdc);


In general you don't paint outside the WM_PAINT handler. If you want your window to be updated, just call InvalidateRect on the area you want to be redrawn. That will trigger the WM_PAINT call which will then repaint the window.

Is there a reason you need to paint the window outside the paint handler?

0

精彩评论

暂无评论...
验证码 换一张
取 消