Clear console window windows

Очистка экрана Clearing the Screen

Существует четыре способа очистки экрана в консольном приложении. There are four ways to clear the screen in a console application.

Пример 1 Example 1

Это рекомендуемый метод с использованием виртуальных последовательностей терминалов для всех новых разработок. This is the recommended method using virtual terminal sequences for all new development. Дополнительные сведения см. в обсуждении классических API консоли и виртуальных последовательностей терминалов . For more information, see the discussion of classic console APIs versus virtual terminal sequences .

Первый способ — настроить приложение для виртуальных выходных последовательностей терминала, а затем вызвать команду «очистить экран». The first method is to set your application up for virtual terminal output sequences and then call the «clear screen» command.

Дополнительные варианты этой команды см. в документации по виртуальным последовательностям, посвященной стиранию экрана . You can find additional variations on this command in the virtual terminal sequences documentation on Erase In Display .

Пример 2 Example 2

Второй метод — написать функцию для прокрутки содержимого экрана или буфера и задать заливку для видимого пространства. The second method is to write a function to scroll the contents of the screen or buffer and set a fill for the revealed space.

Это соответствует поведению командной строки cmd.exe . This matches the behavior of the command prompt cmd.exe .

Пример 3 Example 3

Третий метод заключается в написании функции для программного очистки экрана с помощью функций филлконсолеаутпутчарактер и филлконсолеаутпутаттрибуте . The third method is to write a function to programmatically clear the screen using the FillConsoleOutputCharacter and FillConsoleOutputAttribute functions.

Читайте также:  Драйвера видеокарт для линукса

Этот прием показан в следующем образце кода. The following sample code demonstrates this technique.

Console. Clear Метод

Определение

Удаляет из буфера консоли и ее окна отображаемую информацию. Clears the console buffer and corresponding console window of display information.

Исключения

Ошибка ввода/вывода. An I/O error occurred.

Примеры

В следующем примере Clear метод очищает консоль перед выполнением цикла, предложит пользователю выбрать цвет переднего плана и фона и ввести строку для вывода. The following example uses the Clear method to clear the console before it executes a loop, prompts the user to select a foreground and background color and to enter a string to display. Если пользователь решил не выходить из программы, восстанавливаются исходные цвета и цвет фона консоли, а Clear метод вызывается снова перед повторным выполнением цикла. If the user chooses not to exit the program, the console’s original foreground and background colors are restored and the Clear method is called again before re-executing the loop.

В этом примере используется GetKeyPress метод для проверки выбора пользователем переднего плана и цвета фона. The example relies on a GetKeyPress method to validate the user’s selection of a foreground and background color.

В этом примере демонстрируются CursorLeft CursorTop Свойства и, а SetCursorPosition также Clear методы и. This example demonstrates the CursorLeft and CursorTop properties, and the SetCursorPosition and Clear methods. В примере размещается курсор, который определяет, где будет выполняться следующая запись, чтобы нарисовать 5-символьный прямоугольник на 5 символов, используя сочетание строк «+», «|» и «-«. The example positions the cursor, which determines where the next write will occur, to draw a 5 character by 5 character rectangle using a combination of «+», «|», and «-» strings. Обратите внимание, что прямоугольник может быть нарисован с меньшим количеством шагов, используя сочетание других строк. Note that the rectangle could be drawn with fewer steps using a combination of other strings.

Читайте также:  Какая последняя версия mac os для macbook pro

Комментарии

Использование Clear метода эквивалентно вызову cls команды MS-DOS в окне командной строки. Using the Clear method is equivalent invoking the MS-DOS cls command in the command prompt window. При Clear вызове метода курсор автоматически прокручивается к левому верхнему углу окна, а содержимое буфера экрана устанавливается в пустое значение с использованием текущих фоновых цветов переднего плана. When the Clear method is called, the cursor automatically scrolls to the top-left corner of the window and the contents of the screen buffer are set to blanks using the current foreground background colors.

Попытка вызвать метод, Clear когда выходные данные консольного приложения перенаправляется в файл, вызывает исключение IOException . Attempting to call the Clear method when a console application’s output is redirected to a file throws a IOException. Чтобы избежать этого, всегда заключайте вызов Clear метода в try . catch To prevent this, always wrap a call to the Clear method in a try … catch блок. block.

How do you clear the console screen in C?

Is there a «proper» way to clear the console window in C, besides using system(«cls») ?

13 Answers 13

Well, C doesn’t understand the concept of screen. So any code would fail to be portable. Maybe take a look at conio.h or curses, according to your needs?

Portability is an issue, no matter what library is used.

This function will work on ANSI terminals, demands POSIX. I assume there is a version that might also work on window’s console, since it also supports ANSI escape sequences.

There are some other alternatives, some of which don’t move the cursor to <1,1>.

Читайте также:  Windows как установить переменную среды

For portability, try this:

Then simply call clrscr() . On Windows, it will use conio.h ‘s clrscr() , and on Linux, it will use ANSI escape codes.

If you really want to do it «properly», you can eliminate the middlemen ( conio , printf , etc.) and do it with just the low-level system tools (prepare for a massive code-dump):

A workaround tested on Windows(cmd.exe), Linux(Bash and zsh) and OS X(zsh):

Using macros you can check if you’re on Windows, Linux, Mac or Unix, and call the respective function depending on the current platform. Something as follows:

Since you mention cls , it sounds like you are referring to windows. If so, then this KB item has the code that will do it. I just tried it, and it worked when I called it with the following code:

There is no C portable way to do this. Although various cursor manipulation libraries like curses are relatively portable. conio.h is portable between OS/2 DOS and Windows, but not to *nix variants.

The entire notion of a «console» is a concept outside of the scope of standard C.

If you are looking for a pure Win32 API solution, There is no single call in the Windows console API to do this. One way is to FillConsoleOutputCharacter of a sufficiently large number of characters. Or WriteConsoleOutput You can use GetConsoleScreenBufferInfo to find out how many characters will be enough.

You can also create an entirely new Console Screen Buffer and make the current one.

Оцените статью