Clearing the Screen There are two ways to clear the screen in a console application. The first method is to use the C run-time system function as follows: #include <stdlib.h> void main() { system("cls"); } The system function invokes the cls command provided by the command interpreter to clear the screen. The second method is to write a function to programmatically clear the screen using the FillConsoleOutputCharacter and FillConsoleOutputAttribute functions. The following sample code demonstrates this technique. void cls( HANDLE hConsole ) { COORD coordScreen = { 0, 0 }; // home for the cursor DWORD cCharsWritten; CONSOLE_SCREEN_BUFFER_INFO csbi; DWORD dwConSize; // Get the number of character cells in the current buffer. if( !GetConsoleScreenBufferInfo( hConsole, &csbi )) return; dwConSize = csbi.dwSize.X * csbi.dwSize.Y; // Fill the entire screen with blanks. if( !FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten )) return; // Get the current text attribute. if( !GetConsoleScreenBufferInfo( hConsole, &csbi )) return; // Set the buffer's attributes accordingly. if( !FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )) return; // Put the cursor at its home coordinates. SetConsoleCursorPosition( hConsole, coordScreen ); } |