Search code examples
delphiconsolescreen

Delphi Console XE7 Clearscreen


How I can clear the console screen in a delphi console application (delphi xe6 or higher) I have searched the internet and the help file but cannot seem to find it?


Solution

  • I am trying to find out if there is a function already provided in the delphi units to provide this functionality.

    There is no such function provided by the Delphi runtime library. You will need to write your own function using the operating system services. This article on MSDN explains how to do it: https://support.microsoft.com/en-us/kb/99261

    Translate that like so:

    procedure ClearScreen;
    var
      stdout: THandle;
      csbi: TConsoleScreenBufferInfo;
      ConsoleSize: DWORD;
      NumWritten: DWORD;
      Origin: TCoord;
    begin
      stdout := GetStdHandle(STD_OUTPUT_HANDLE);
      Win32Check(stdout<>INVALID_HANDLE_VALUE);
      Win32Check(GetConsoleScreenBufferInfo(stdout, csbi));
      ConsoleSize := csbi.dwSize.X * csbi.dwSize.Y;
      Origin.X := 0;
      Origin.Y := 0;
      Win32Check(FillConsoleOutputCharacter(stdout, ' ', ConsoleSize, Origin, 
        NumWritten));
      Win32Check(FillConsoleOutputAttribute(stdout, csbi.wAttributes, ConsoleSize, Origin, 
        NumWritten));
      Win32Check(SetConsoleCursorPosition(stdout, Origin));
    end;