Clear the Screen using WinApi functions

vegaseat 1 Tallied Votes 720 Views Share

Many of the code samples on the internet are written in Turbo C. The clrscr() function litters these samples, and even to this day people want to wipe your screen. You can use system("CLS"), but that uses a DOS command. DOS commands are with us only at the whim of William the Mighty. Here is the Windows version of clearing the console screen with WinApi functions, in the hope that these functions will stay around a little longer.

// test of the official Windows Console clear the screen function
// tested with Pelles C    vegaseat     26mar2005

#include <stdio.h>

void clrscr(void);

#include <windows.h> 

void clrscr(void)
{
  COORD coordScreen = { 0, 0 };  // upper left corner
  DWORD cCharsWritten;
  DWORD dwConSize;
  HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
  CONSOLE_SCREEN_BUFFER_INFO  csbi;
    
  GetConsoleScreenBufferInfo(hCon, &csbi);
  dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
  // fill with spaces
  FillConsoleOutputCharacter(hCon, TEXT(' '), dwConSize, coordScreen, &cCharsWritten);
  GetConsoleScreenBufferInfo(hCon, &csbi);
  FillConsoleOutputAttribute(hCon, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);
  // cursor to upper left corner
  SetConsoleCursorPosition(hCon, coordScreen);
}


int main(void)
{
  int k;
  
  for(k = 0; k < 25; k++)
  {
    printf("Test........\n");
  }
  printf("Press Enter...");
  getchar();
  clrscr();
  getchar();  // wait  
  return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.