Microsoft KB Archive/99261

{|
 * width="100%"|

HOWTO: Performing Clear Screen (CLS) in a Console Application

 * }

Q99261

-

The information in this article applies to:


 * Microsoft Win32 Application Programming Interface (API), used with:
 * the operating system: Microsoft Windows NT, versions 3.51, 4.0
 * Microsoft Windows 95
 * the operating system: Microsoft Windows 2000

-

SUMMARY
Some non-Microsoft versions of C++ provide a clrscr function for clearing the screen in a DOS application. However, there is no Win32 Application Programming Interface (API) or C-Runtime function that will perform this function.

There are two ways to accomplish this task for a Win32 console application. The first method is to use the system function as follows:

#include 

void main {  system(&quot;cls&quot;); }

The second method is to write a function that will programmatically clear the screen. That method is described in the More Information section which follows.

MORE INFORMATION
The following function clears the screen:

 /* Standard error macro for reporting API errors */ on line %d\n&quot;, __FILE__, GetLastError, api, __LINE__);}
 * 1) define PERR(bSuccess, api){if(!(bSuccess)) printf(&quot;%s:Error %d from %s \

void cls( HANDLE hConsole ) {   COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */ BOOL bSuccess; DWORD cCharsWritten; CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ DWORD dwConSize;                /* number of character cells in                                        the current buffer */

/* get the number of character cells in the current buffer */

bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi ); PERR( bSuccess, &quot;GetConsoleScreenBufferInfo&quot; ); dwConSize = csbi.dwSize.X * csbi.dwSize.Y;

/* fill the entire screen with blanks */

bSuccess = FillConsoleOutputCharacter( hConsole, (TCHAR) ' ',      dwConSize, coordScreen, &cCharsWritten ); PERR( bSuccess, &quot;FillConsoleOutputCharacter&quot; );

/* get the current text attribute */

bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi ); PERR( bSuccess, &quot;ConsoleScreenBufferInfo&quot; );

/* now set the buffer's attributes accordingly */

bSuccess = FillConsoleOutputAttribute( hConsole, csbi.wAttributes,      dwConSize, coordScreen, &cCharsWritten ); PERR( bSuccess, &quot;FillConsoleOutputAttribute&quot; );

/* put the cursor at (0, 0) */

bSuccess = SetConsoleCursorPosition( hConsole, coordScreen ); PERR( bSuccess, &quot;SetConsoleCursorPosition&quot; ); return; } Additional query words: clearscreen

Keywords : _IK kbAPI kbConsole kbKernBase kbOSWinNT351 kbOSWinNT400 kbOSWin2000 kbDSupport kbGrpDSKernBase

Issue type : kbhowto

Technology : kbAudDeveloper kbWin32sSearch kbWin32API