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)

{

   system("cls");

   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;

      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(L"The previous screen was cleared!\n");

}

 

int wmain(int argc, WCHAR **argv)

{

    HANDLE hStdout;

 

    wprintf(L"Some text displayed on standard output.\n");

    wprintf(L"Sleeping 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.

 

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 >