Clearing the Console Screen
There are two ways to clear the screen in a console application.
Clear Screen: Example 1
The first method is to use the C run-time system function. The system function invokes the cls command provided by the command interpreter to clear the screen.
#include <stdlib.h>
int wmain(int argc, WCHAR **argv)
{
system(cls);
return 0;
}
It is similar to running the cls command at the command prompt.
Clear Screen: Example 2
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.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
#include <windows.h>
#include <stdio.h>
void cls(HANDLE hConsole)
{
// home for the cursor
COORD coordScreen = {0, 0};
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, (WCHAR)' ', 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);
wprintf(LThe previous screen was cleared!\n);
}
int wmain(int argc, WCHAR **argv)
{
HANDLE hStdout;
wprintf(LSome text displayed on standard output.\n);
wprintf(LSleeping for a while...\n);
// sleep for 5000 ms
Sleep(5000);
// Clear screen and exit
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
cls(hStdout);
return 0;
}
Build and run the project. The following screenshots are sample outputs.