Reducing Flicker in Console Applications

 
 
Everyone who starts C++ has to start somewhere, and that place is nearly always the console window. The console window is a very quick way to jump into programming without having to worry about the overhead of managing the window, loading and displaying graphics, etc…

Along with the ease of use, the console brings a many limitations to programming real time applications. The most glaring limitation is the way the console redraws itself. Real time applications must clear the screen and redraw every element to produce an updated image. This code will cause some flickering…

Bad

while(true)
{
Update();

system("cls"); //Clears the entire screen to show nothing

DrawElements(); //Draws everything on the console screen

//I suggest you sleep for 100ms or so here

}


That code wouldnt work because there would be a fraction of a second where the screen will be blank and you may even be able to see it drawing, dependent on how the objects on the screen were drawn.

There is some code in windows.h that can help us.

Good

#include <windows.h>

while(true)
{
Update();

LockWindowUpdate(GetConsoleWindow()); //Locks the console window so the OS doesn\'t draw it

system("cls"); // Clears the entire screen to show nothing

DrawElements(); // Draws everything on the console screen

LockWindowUpdate(NULL); //Removes the lock from the console window

//I suggest you sleep for 100ms or so here

}


This code will effectively stop Windows from redrawing the window in the time we are clearing it and redrawing it.

Window Locking Functions

GetConsoleWindow() – Returns a handle to the current console window

LockWindowUpdate(HWND) – Takes in a handle to a window to lock, if NULL is passed through it will unlock the window

Alternatively: UnlockWindowUpdate() can be used like LockWindowUpdate(NULL)

This piece of code increase the visual appeal of my project, Boggle, quite a bit. Unfortunately I hadn’t learned it earlier and some of my other projects had suffered from this limitation. I will be posting two of my projects soon so you can see what it was like before I used this code, and after I used this code.

Try it out and leave some comments!

Comments are closed.