Windows Character Mode Application 5




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)



   return 0;



It is similar to running the cls command at the command prompt.


Clearing the Console Screen: Using the CLS command 1


Clearing the Console Screen: Using the CLS command 2


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;


      DWORD dwConSize;


      // Get the number of character cells in the current buffer

      if(!GetConsoleScreenBufferInfo(hConsole, &csbi))


      dwConSize = csbi.dwSize.X * csbi.dwSize.Y;


      // Fill the entire screen with blanks

      if(!FillConsoleOutputCharacter(hConsole, (WCHAR)' ', dwConSize, coordScreen, &cCharsWritten))



      // Get the current text attribute.

      if(!GetConsoleScreenBufferInfo(hConsole, &csbi))



      // Set the buffer's attributes accordingly.

      if(!FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten))



      // 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



    // Clear screen and exit

    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);


    return 0;



Build and run the project. The following screenshots are sample outputs.


Clearing the Console Screen: Using the CLS command 3


Clearing the Console Screen: Using the CLS command 4




< Character Mode App. Win32 Programming 4 | Win32 Programming | Character Mode App. Index | Character Mode App. Win32 Programming 6 >