Handmade Hero»Forums»Code
107 posts
Rectangle(); flicker and moving fast
Edited by C_Worm on Reason: Initial post
I have a program that draws a rectangle and fills it with a green color using GDI functions:

Rectangle();
FillRect();


The problems are:

1. The Rectangle flickers like crazy. I guess this is due to it being repainted every frame and the whole client area is somehow
begin invalidated.
How would this be solved?

2. When i press the arrows, the rectangle is moving. However, it is moving SUPER fast even though it is just incremented by 1
pixel a frame.
I guess that this has something to do with the frame rate. but im not sure?
what do you think? and how would one make the rectangle move slower?

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#include <windows.h>

static bool keyStates[256]= {};

HBRUSH green = CreateSolidBrush(RGB(0, 255, 0));

static bool running = true;

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE Instance, HINSTANCE prevInstance, PSTR cmdLine, int cmdShow)
{

	WNDCLASS wc = {};
	HWND hwnd = {};
	MSG message = {};
	char ClassName[] = "CJ_winapi_002";

	wc.hInstance = Instance;
	wc.lpfnWndProc = WndProc;
	wc.style = CS_VREDRAW | CS_HREDRAW | CS_OWNDC;
	wc.lpszClassName = ClassName;
	wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);

	if(!RegisterClass(&wc))
	{
		MessageBox(0, "Register Class Fail", "Couldn't Register Class", 0);
	}
	
	RECT rect = {0, 0, 800, 600};
	AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, 0);
	int windowWidth = (rect.right - rect.left);
	int windowHeight = (rect.bottom - rect.top);


	if(!(hwnd = CreateWindow(ClassName, ClassName, WS_OVERLAPPEDWINDOW, 0, 0, windowWidth, windowHeight, 0, 0, Instance, 0)))
	{
		MessageBox(0, "Create Window Fail", "Couldn't Create Window", 0);
	}	

	ShowWindow(hwnd, SW_SHOW);

	

	int x = 0, 
	    y = 0, 
	    width = 100, 
	    height = 100;

	RECT fillR = { x, y, width, height };

	HDC hdc = GetDC(hwnd);

	LARGE_INTEGER lastCount;	
	QueryPerformanceCounter(&lastCount);

	while(running)
	{
		while(PeekMessage(&message, 0, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&message);
			DispatchMessage(&message);
		}


		Rectangle(hdc, fillR.left, fillR.top, fillR.right, fillR.bottom);
		FillRect(hdc, &fillR, green);
		if(keyStates[VK_UP])
		{

			Rectangle(hdc, fillR.left, --fillR.top, fillR.right, --fillR.bottom);
			FillRect(hdc, &fillR, green);
		}
		if(keyStates[VK_DOWN])
		{

			Rectangle(hdc, fillR.left, ++fillR.top, fillR.right, ++fillR.bottom);
			FillRect(hdc, &fillR, green);
		}
		if(keyStates[VK_RIGHT])
		{

			Rectangle(hdc, ++fillR.left, fillR.top, ++fillR.right, fillR.bottom);
			FillRect(hdc, &fillR, green);
		}
		if(keyStates[VK_LEFT])
		{

			Rectangle(hdc, --fillR.left, fillR.top, --fillR.right, fillR.bottom);
			FillRect(hdc, &fillR, green);
		}


		char buffer[256] = {};
		LARGE_INTEGER endCount;

		QueryPerformanceCounter(&endCount);
		_int64 resultCount = (_int64)(endCount.QuadPart - lastCount.QuadPart);

		lastCount = endCount;

		wsprintf(buffer, "Performance Count: %d\n", resultCount);
		OutputDebugString(buffer);
	
		
	}

	ReleaseDC(hwnd, hdc);
	return 0;
}




LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM WParam, LPARAM LParam)
{

	int VK_CODE = WParam;

	switch(message)
	{
		case WM_KEYDOWN:
		{

		if(keyStates[WParam] == false)
		{
			if(WParam == VK_UP)
			{
				SetWindowText(hwnd, "isDown: UP");	
				OutputDebugString("isDown: UP\n");
				keyStates[WParam] = true;
			}
			if(WParam == VK_DOWN)
			{
				SetWindowText(hwnd, "isDown: DOWN");	
				OutputDebugString("isDown: DOWN\n");
				keyStates[WParam] = true;
			}
			if(WParam == VK_RIGHT)
			{
				SetWindowText(hwnd, "isDown: RIGHT");	
				OutputDebugString("isDown: RIGHT\n");
				keyStates[WParam] = true;
			}
			if(WParam == VK_LEFT)
			{
				SetWindowText(hwnd, "isDown: LEFT");	
				OutputDebugString("isDown: LEFT\n");
				keyStates[WParam] = true;
			}
		}

		} break;  

		case WM_KEYUP:
		{
			if(WParam == VK_UP)
			{
				keyStates[WParam] = false;
				SetWindowText(hwnd, "wasDown: UP");	
				OutputDebugString("wasDown: UP\n");
			}
			if(WParam == VK_DOWN)
			{
				keyStates[WParam] = false;
				SetWindowText(hwnd, "wasDown: DOWN");	
			}
			if(WParam == VK_RIGHT)
			{
				keyStates[WParam] = false;
				SetWindowText(hwnd, "wasDown: RIGHT");	
			}
			if(WParam == VK_LEFT)
			{
				keyStates[WParam] = false;
				SetWindowText(hwnd, "wasDown: LEFT");	
			}

		} break;

		case WM_PAINT:
		{
			PAINTSTRUCT ps;
			HDC hdc = BeginPaint(hwnd, &ps);


			EndPaint(hwnd, &ps);

		} break;	

		case WM_DESTROY:
			{
				PostQuitMessage(1337);
				running = false;
			} break;	
	}

	return DefWindowProc(hwnd, message, WParam, LParam);
}

Simon Anciaux
1337 posts
Rectangle(); flicker and moving fast
If you use PeekMessage instead of GetMessage, the application doesn't pause if there are no messages, and since it's in an infinite loop, your application will run as fast as it can, meaning a lot more than 60 frame per second and your CPU will use a core at 100%. So you would need some way to pause the application to have about 60 fps (or the frame rate you want).

A solution would be to put "Sleep( 16 );" (1000/60) somewhere in the loop to make the application run at about 60 fps. But that's not precise and you should not rely on that if you need reproducible computations.

Another way would be to call DwmFlush after you draw to wait for the next frame buffer flip. This will not work on Windows 7 or lower when aero is disabled (classic theme). It should always work on Windows 8 and up. That would also take care of the flicker I believe.
107 posts
Rectangle(); flicker and moving fast
So i tried to use sleep(16); and it is making things A LOT BETTER, almost perfect!

however there's still a LITTLE BIT of a flicker left that shows in random intervalls, why would this be?

i have tried putting the sleep function after and before the FillRect() funtion but it doesn't seem to matter, i also
changed the sleep() intervall and added the timeBeginPeriod(1);

but the slight flicker persist!


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#include <windows.h>

static bool keyStates[256]= {};

HBRUSH green = CreateSolidBrush(RGB(0, 255, 0));
HBRUSH red = CreateSolidBrush(RGB(255, 0, 0));

static bool running = true;

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE Instance, HINSTANCE prevInstance, PSTR cmdLine, int cmdShow)
{

	WNDCLASS wc = {};
	HWND hwnd = {};
	MSG message = {};
	char ClassName[] = "CJ_winapi_002";

	wc.hInstance = Instance;
	wc.lpfnWndProc = WndProc;
	wc.style = CS_VREDRAW | CS_HREDRAW | CS_OWNDC;
	wc.lpszClassName = ClassName;
	wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);

	if(!RegisterClass(&wc))
	{
		MessageBox(0, "Register Class Fail", "Couldn't Register Class", 0);
	}
	
	RECT rect = {0, 0, 800, 600};
	AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, 0);
	int windowWidth = (rect.right - rect.left);
	int windowHeight = (rect.bottom - rect.top);


	if(!(hwnd = CreateWindow(ClassName, ClassName, WS_OVERLAPPEDWINDOW, 0, 0, windowWidth, windowHeight, 0, 0, Instance, 0)))
	{
		MessageBox(0, "Create Window Fail", "Couldn't Create Window", 0);
	}	

	ShowWindow(hwnd, SW_SHOW);

	HDC hdc = GetDC(hwnd);
	int x = 0, 
	    y = 0, 
	    width = 100, 
	    height = 100;

	int vel = 5;
	RECT greenR = { x, y, width, height };
	RECT redR = { x, y, width, height };
	
	timeBeginPeriod(10);
	LARGE_INTEGER lastCount;	
	QueryPerformanceCounter(&lastCount);

	while(running)
	{

		Sleep(16);

		while(PeekMessage(&message, 0, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&message);
			DispatchMessage(&message);
		}


		if(keyStates['W'])
		{

			redR.bottom -= vel;
			redR.top -= vel;
		}
		if(keyStates['S'])
		{

			redR.bottom += vel;
			redR.top += vel;
		}
		if(keyStates['D'])
		{

			redR.left += vel;
			redR.right += vel;
		}
		if(keyStates['A'])
		{

			redR.left -= vel;
			redR.right -= vel;
		}
		if(keyStates[VK_UP])
		{

			greenR.bottom -= vel;
			greenR.top -= vel;
		}
		if(keyStates[VK_DOWN])
		{

			greenR.bottom += vel;
			greenR.top += vel;
		}
		if(keyStates[VK_RIGHT])
		{

			greenR.left += vel;
			greenR.right += vel;
		}
		if(keyStates[VK_LEFT])
		{

			greenR.left -= vel;
			greenR.right -= vel;
		}

		FillRect(hdc, &greenR, green);
		FillRect(hdc, &redR, red);
		InvalidateRect(hwnd, 0, true);

		char buffer[256] = {};
		LARGE_INTEGER endCount;

		QueryPerformanceCounter(&endCount);
		_int64 resultCount = (_int64)(endCount.QuadPart - lastCount.QuadPart);

		lastCount = endCount;

		wsprintf(buffer, "Performance Count: %d\n", resultCount);
		OutputDebugString(buffer);
		
		
	}

	ReleaseDC(hwnd, hdc);
	return 0;
}




LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM WParam, LPARAM LParam)
{

	int VK_CODE = WParam;

	switch(message)
	{
		case WM_KEYDOWN:
		{

		if(keyStates[WParam] == false)
		{
			if(WParam == VK_UP)
			{
				OutputDebugString("isDown: UP\n");
				keyStates[WParam] = true;
			}
			if(WParam == VK_DOWN)
			{
				OutputDebugString("isDown: DOWN\n");
				keyStates[WParam] = true;
			}
			if(WParam == VK_RIGHT)
			{
				OutputDebugString("isDown: RIGHT\n");
				keyStates[WParam] = true;
			}
			if(WParam == VK_LEFT)
			{
				OutputDebugString("isDown: LEFT\n");
				keyStates[WParam] = true;
			}
			if(WParam == VK_ESCAPE)
			{
				running = false;
			}
			if(WParam == 'W')
			{
				keyStates['W'] = true;
			}
			if(WParam == 'A')
			{
				keyStates['A'] = true;
			}
			if(WParam == 'S')
			{
				keyStates['S'] = true;
			}
			if(WParam == 'D')
			{
				keyStates['D'] = true;
			}
		}

		} break;  

		case WM_KEYUP:
		{
			if(WParam == VK_UP)
			{
				keyStates[WParam] = false;
				OutputDebugString("wasDown: UP\n");
			}
			if(WParam == VK_DOWN)
			{
				keyStates[WParam] = false;
			}
			if(WParam == VK_RIGHT)
			{
				keyStates[WParam] = false;
			}
			if(WParam == VK_LEFT)
			{
				keyStates[WParam] = false;
			}
			if(WParam == 'W')
			{
				keyStates['W'] = false;
			}
			if(WParam == 'A')
			{
				keyStates['A'] = false;
			}
			if(WParam == 'S')
			{
				keyStates['S'] = false;
			}
			if(WParam == 'D')
			{
				keyStates['D'] = false;
			}

		} break;

		case WM_PAINT:
		{
			PAINTSTRUCT ps;
			HDC hdc = BeginPaint(hwnd, &ps);


			EndPaint(hwnd, &ps);

		} break;	

		case WM_DESTROY:
			{
				PostQuitMessage(1337);
				running = false;
			} break;	
	}

	return DefWindowProc(hwnd, message, WParam, LParam);
}
Simon Anciaux
1337 posts
Rectangle(); flicker and moving fast
Edited by Simon Anciaux on Reason: typo
I never used GDI so I'm not sure. I looks like there is clear to white and then it draws your rectangles, but sometimes the application is presented to the screen inbetween the clear and the rectangles drawing. That's why you'd better call DwmFlush after your drawing to "wait for the vsync". If you call DwmFlush, you need remove the sleep( 16 ).

Another way that could work would be to draw to an off-screen bitmap and than use BitBlt or StretchBlt in the WM_PAINT message to copy it to the screen. Something like what Casey does at the beginning of handmade hero. It should remove the flicker but you might get screen tearing if the compositor is off. Using rectangles seems to be an example on msdn.

Hopefully somebody that knows GDI will come by this thread.
107 posts
Rectangle(); flicker and moving fast
Allright, thank you for your respons! :)