a design problem about the message WM_PAINT and SetTimer function

Rer 80 Reputation points
2023-08-20T11:12:35.3633333+00:00

(Images are below)I am trying making a tetris game with winapi. I have defined a 10 * 20 RECT array(mapRect[10][20]), which I use to print my map(the map info is stored by a structure called maptrn, only including a 10 * 20 int array). I use setTimer() function to update mapRect for a printing test(), so I add a function called drawMap() (the function is to invalidate all mapRect members) into TimerProc() to invalidate them. But the problem is that after a while the window is redrawn abnormally, and, more exactly, it didn't execute some of the redraw commands, and the style of all the messageboxes are changed. How can I solve the problem?


for(int i = 0; i < HEIGHT; i++) for(int j = 0; j < WIDTH; j++)            InvalidateRect(hwnd, &MapRect[i][j], TRUE);
}

for(int i = 0; i < HEIGHT; i++) for(int j = 0; j < WIDTH; j++)            FillRect(hdc, &MapRect[i][j], CreateSolidBrush(MinoColor[mt.mapTrn[i][j]]));
}

void CALLBACK timerFunc(HWND hwnd, UINT uMsg, UINT_PTR nTimerID, DWORD dwTime)
{
    mino.type = (mino.type + 1) % 8;
    invalidMap(hwnd);
}

...

//In case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);


FillRect(hdc, &MsgRect, CreateSolidBrush(BGCOLOR));

//DrawText(hdc, TEXT("MsgRect Test"), -1, &MsgRect, 0);
//DT_SINGLELINE | DT_CENTER | DT_VCENTER            

RectPrintf(hdc, &MsgRect, TEXT("This is %d"), combine(map, mino).mapTrn[1][1]);


drawMap(combine(newMap, mino), hdc);            
break;

中文:我在用winapi写一个俄罗斯方块游戏。开始我定义了一个mapRect的RECT[10][20]类型的数组,然后我用maptrn(我定义的,包含10 * 20的int数组的结构体)的一个对象来记录地图数据。我还用到了setTimer函数来更新地图的打印测试,所以在计时器proc函数里面加入了drawMap函数(我定义的,将所有mapRect给invalidate掉)。但是问题在于,程序开始一段时间后,他会出现更新上的错误,更准确地说,是某些代码好像没执行,以及messagebox的风格改变了。我应该如何解决?

屏幕截图 2023-08-20 185516

pic1 normal display屏幕截图 2023-08-20 185556

pic2 abnormal display (after the blue text appears in debug console)

屏幕截图 2023-08-20 185614

pic3 abnormal msgbox(the style and text(original one is "Do you want to quit Tetris?"))

屏幕截图 2023-08-20 185658

pic4 when this text appears the application doesn't work well as I think

Windows development | Windows API - Win32
Windows for business | Windows Client for IT Pros | User experience | Other
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2023-08-20T11:28:12.8366667+00:00

    Probably you are creating too many brushes using CreateSolidBrush. If you create a local brush, you must destroy it, like this:

    HBRUSH b = CreateSolidBrush(...)
    FillRect(..., b);
    DeleteObject(b);
    

    Or maybe you can pre-create some of the brushes, keep to some variables, and re-use them multiple times.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.