SetConsoleScreenBufferSize function
This document describes console platform functionality that is no longer a part of our ecosystem roadmap. We do not recommend using this content in new products, but we will continue to support existing usages for the indefinite future. Our preferred modern solution focuses on virtual terminal sequences for maximum compatibility in cross-platform scenarios. You can find more information about this design decision in our classic console vs. virtual terminal document.
Changes the size of the specified console screen buffer.
Syntax
Parameters
hConsoleOutput [in]
A handle to the console screen buffer. The handle must have the GENERIC_READ access right. For more information, see Console Buffer Security and Access Rights.
dwSize [in]
A COORD structure that specifies the new size of the console screen buffer, in character rows and columns. The specified width and height cannot be less than the width and height of the console screen buffer’s window. The specified dimensions also cannot be less than the minimum size allowed by the system. This minimum depends on the current font size for the console (selected by the user) and the SM_CXMIN and SM_CYMIN values returned by the GetSystemMetrics function.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
This API is not recommended and does not have a virtual terminal equivalent. This decision intentionally aligns the Windows platform with other operating systems where the user is granted full control over this presentation option. Applications remoting via cross-platform utilities and transports like SSH may not work as expected if using this API.
Буферы экрана консоли Console Screen Buffers
Буфер экрана — это двумерный массив символов и данных о цвете для вывода в окне консоли. A screen buffer is a two-dimensional array of character and color data for output in a console window. Консоль может иметь несколько буферов экрана. A console can have multiple screen buffers. Буфер активного экрана отображается на экране. The active screen buffer is the one that is displayed on the screen.
Система создает буфер экрана каждый раз при создании новой консоли. The system creates a screen buffer whenever it creates a new console. Чтобы открыть дескриптор для активного буфера экрана консоли, укажите значение CONOUT$ в вызове к функции CreateFile. To open a handle to a console’s active screen buffer, specify the CONOUT$ value in a call to the CreateFile function. Процесс может использовать функцию CreateConsoleScreenBuffer для создания дополнительных буферов экрана консоли. A process can use the CreateConsoleScreenBuffer function to create additional screen buffers for its console. Новый буфер экрана не активен, пока его дескриптор не будет указан в вызове функции SetConsoleActiveScreenBuffer. A new screen buffer is not active until its handle is specified in a call to the SetConsoleActiveScreenBuffer function. Но доступ к буферам экрана для чтения и записи можно получить независимо от того, активны они или неактивны. However, screen buffers can be accessed for reading and writing whether they are active or inactive.
Каждый буфер экрана содержит собственный двумерный массив записей с данными о символах. Each screen buffer has its own two-dimensional array of character information records. Данные о каждом символе хранятся в структуре CHAR_INFO, которая указывает символ Юникода или ANSI, а также цвета переднего плана и фона для отображения символа. The data for each character is stored in a CHAR_INFO structure that specifies the Unicode or ANSI character and the foreground and background colors in which that character is displayed.
Некоторые свойства, связанные с буфером экрана, можно задать независимо для каждого буфера. A number of properties associated with a screen buffer can be set independently for each screen buffer. Это означает, что изменение активного буфера экрана может привести к значительному изменению внешнего вида окна консоли. This means that changing the active screen buffer can have a dramatic effect on the appearance of the console window. Свойства, связанные с буфером экрана, включают следующие: The properties associated with a screen buffer include:
- Размер буфера экрана, в символьных строках и столбцах. Screen buffer size, in character rows and columns.
- Атрибуты текста (цвета переднего плана и фона для отображения текста, записываемого функцией WriteFile или WriteConsole). Text attributes (foreground and background colors for displaying text to be written by the WriteFile or WriteConsole function).
- Размер и расположение окна (прямоугольная область буфера экрана консоли, отображаемого в окне консоли). Window size and location (the rectangular region of the console screen buffer that is displayed in the console window).
- Позиция, внешний вид и видимость курсора. Cursor position, appearance, and visibility.
- Режимы вывода (ENABLE_PROCESSED_OUTPUT и ENABLE_WRAP_AT_EOL_OUTPUT). Output modes (ENABLE_PROCESSED_OUTPUT and ENABLE_WRAP_AT_EOL_OUTPUT). Дополнительные сведения о режимах вывода консоли см. в статье Высокоуровневые режимы консоли. For more information about console output modes, see High-Level Console Modes.
Созданный буфер экрана содержит пробелы в каждой из позиций. When a screen buffer is created, it contains space characters in every position. Его курсор отображается и размещается в точке начала буфера (0,0), при этом окно располагается таким образом, что его верхний левый угол находится в месте начала буфера. Its cursor is visible and positioned at the buffer’s origin (0,0), and the window is positioned with its upper left corner at the buffer’s origin. Размер буфера экрана консоли, размер окна, атрибуты текста и внешний вид курсора определяются пользователем или системными параметрами по умолчанию. The size of the console screen buffer, the window size, the text attributes, and the appearance of the cursor are determined by the user or by the system defaults. Чтобы получить текущие значения различных свойств, связанных с буфером экрана консоли, используйте функции GetConsoleScreenBufferInfo, GetConsoleCursorInfo и GetConsoleMode. To retrieve the current values of the various properties associated with the console screen buffer, use the GetConsoleScreenBufferInfo, GetConsoleCursorInfo, and GetConsoleMode functions.
Приложения, изменяющие любые свойства буфера экрана консоли, должны либо создать собственный буфер экрана, либо сохранить состояние наследуемого буфера экрана во время запуска и восстановить его при выходе. Applications that change any of the console screen buffer properties should either create their own screen buffer or save the state of the inherited screen buffer during startup and restore it at exit. Такое скоординированное поведение гарантирует, что изменения не будут затрагивать другие приложения, совместно использующие один сеанс консоли. This cooperative behavior is required to ensure that other applications sharing the same console session are not impacted by the changes.
Рекомендуется использовать режим альтернативного буфера, а не создавать второй буфер экрана для этой цели. It is recommended to use the alternate buffer mode going forward, if possible, instead of creating a second screen buffer for this purpose. Режим альтернативного буфера обеспечивает повышенную совместимость для удаленных устройств и с другими платформами. Alternate buffer mode offers increased compatibility across remote devices and with other platforms. Дополнительные сведения см. в статье о классических API консоли и виртуальном терминале. Please see our discussion on classic console APIs versus virtual terminal for more information.
Внешний вид и расположение курсора Cursor Appearance and Position
Курсор буфера экрана может быть видимым или скрытым. A screen buffer’s cursor can be visible or hidden. Если он отображается, курсор может иметь самый разный вид — от горизонтальной линии внизу ячейки до полного заполнения символьной ячейки. When it is visible, its appearance can vary, ranging from completely filling a character cell to appearing as a horizontal line at the bottom of the cell. Чтобы получить сведения о внешнем виде и видимости курсора, используйте функцию GetConsoleCursorInfo. To retrieve information about the appearance and visibility of the cursor, use the GetConsoleCursorInfo function. Эта функция сообщает, виден ли курсор, и описывает вид курсора с указанием процентного отношения заполнения им символьной ячейки. This function reports whether the cursor is visible and describes the appearance of the cursor as the percentage of a character cell that it fills. Чтобы задать внешний вид и видимость курсора, используйте функцию SetConsoleCursorInfo. To set the appearance and visibility of the cursor, use the SetConsoleCursorInfo function.
Высокоуровневые функции ввода-вывода консоли записывают символы в текущее расположение курсора и переводят его в следующую позицию. Characters written by the high-level console I/O functions are written at the current cursor location, advancing the cursor to the next location. Чтобы определить текущую позицию курсора в системе координат буфера экрана, используйте функцию GetConsoleScreenBufferInfo. To determine the current cursor position in the coordinate system of a screen buffer, use GetConsoleScreenBufferInfo. Вы можете использовать функцию SetConsoleCursorPosition, чтобы задавать позицию курсора и таким образом управлять размещением текста, который записывается высокоуровневыми функциями или выводится ими. You can use SetConsoleCursorPosition to set the cursor position and, thereby, control the placement of text that is written or echoed by the high-level I/O functions. Если переместить курсор, текст в новом расположении будет перезаписан. If you move the cursor, text at the new cursor location is overwritten.
Не рекомендуется использовать низкоуровневые функции для поиска позиции курсора. Using the low-level functions to find the cursor position is discouraged. При необходимости используйте последовательности виртуального терминала для запрашивания этой позиции для расширенных макетов. It is recommended to use virtual terminal sequences to query this position if necessary for advanced layouts. Дополнительные сведения о предпочтительных последовательностях виртуального терминала см. в документе о классических функциях и виртуальном терминале . More information about preferring virtual terminal sequences can be found in the classic functions versus virtual terminal document.
Расположение, внешний вид и видимость курсора задаются для каждого буфера экрана независимо. The position, appearance, and visibility of the cursor are set independently for each screen buffer.
Атрибуты символов Character Attributes
Атрибуты символов можно разделить на два класса: Color и DBCS. Character attributes can be divided into two classes: color and DBCS. Приведенные ниже атрибуты определены в файле заголовка WinCon.h . The following attributes are defined in the WinCon.h header file.
attribute Attribute | Значение Meaning |
---|---|
FOREGROUND_BLUE FOREGROUND_BLUE | Текст содержит синий цвет. Text color contains blue. |
FOREGROUND_GREEN FOREGROUND_GREEN | Текст содержит зеленый цвет. Text color contains green. |
FOREGROUND_RED FOREGROUND_RED | Текст содержит красный цвет. Text color contains red. |
FOREGROUND_INTENSITY FOREGROUND_INTENSITY | Для цвета текста изменена интенсивность. Text color is intensified. |
BACKGROUND_BLUE BACKGROUND_BLUE | Фон содержит синий цвет. Background color contains blue. |
BACKGROUND_GREEN BACKGROUND_GREEN | Фон содержит зеленый цвет. Background color contains green. |
BACKGROUND_RED BACKGROUND_RED | Фон содержит красный цвет. Background color contains red. |
BACKGROUND_INTENSITY BACKGROUND_INTENSITY | Для цвета фона изменена интенсивность. Background color is intensified. |
COMMON_LVB_LEADING_BYTE COMMON_LVB_LEADING_BYTE | Начальный байт. Leading byte. |
COMMON_LVB_TRAILING_BYTE COMMON_LVB_TRAILING_BYTE | Конечный байт. Trailing byte. |
COMMON_LVB_GRID_HORIZONTAL COMMON_LVB_GRID_HORIZONTAL | Верхний горизонтальный. Top horizontal. |
COMMON_LVB_GRID_LVERTICAL COMMON_LVB_GRID_LVERTICAL | Левый вертикальный. Left vertical. |
COMMON_LVB_GRID_RVERTICAL COMMON_LVB_GRID_RVERTICAL | Правый вертикальный. Right vertical. |
COMMON_LVB_REVERSE_VIDEO COMMON_LVB_REVERSE_VIDEO | Обратить атрибуты переднего плана и фона. Reverse foreground and background attributes. |
COMMON_LVB_UNDERSCORE COMMON_LVB_UNDERSCORE | Знак подчеркивания. Underscore. |
Атрибуты переднего плана задают цвет текста. The foreground attributes specify the text color. Атрибуты фона задают цвет, используемый для заполнения фона ячейки. The background attributes specify the color used to fill the cell’s background. Другие атрибуты используются с DBCS. The other attributes are used with DBCS.
Приложение может сочетать константы переднего плана и фона для отображения различных цветов. An application can combine the foreground and background constants to achieve different colors. Например, следующее сочетание приводит к отображению светло-голубого текста на синем фоне. For example, the following combination results in bright cyan text on a blue background.
FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE
Если константа фона не указана, фон будет черным. Если не указана ни одна из констант переднего плана, текст будет черным. If no background constant is specified, the background is black, and if no foreground constant is specified, the text is black. Например, следующее сочетание приводит к отображению черного цвета на белом фоне. For example, the following combination produces black text on a white background.
BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED
Каждая символьная ячейка буфера экрана хранит атрибуты цвета для цветов, используемых при отрисовке переднего плана (текста) и фона такой ячейки. Each screen buffer character cell stores the color attributes for the colors used in drawing the foreground (text) and background of that cell. Приложение может задавать данные цвета отдельно для каждой символьной ячейки, сохраняя данные в элементе Attributes структуры CHAR_INFO для каждой ячейки. An application can set the color data for each character cell individually, storing the data in the Attributes member of the CHAR_INFO structure for each cell. Текущие текстовые атрибуты для каждого буфера экрана используются для символов, которые последовательно записываются или выводятся высокоуровневыми функциями. The current text attributes of each screen buffer are used for characters subsequently written or echoed by the high-level functions.
Приложение может использовать функцию GetConsoleScreenBufferInfo, чтобы определить текущие атрибуты текста для буфера экрана, и функцию SetConsoleTextAttribute, чтобы задать атрибуты символов. An application can use GetConsoleScreenBufferInfo to determine the current text attributes of a screen buffer and the SetConsoleTextAttribute function to set the character attributes. Изменение атрибутов буфера экрана не повлияет на отображение уже записанных символов. Changing a screen buffer’s attributes does not affect the display of characters previously written. Такие атрибуты текста не влияют на символы, записанные низкоуровневыми функциями ввода-вывода консоли (например, WriteConsoleOutput или WriteConsoleOutputCharacter), которые явно задают атрибуты для каждой записываемой ячейки или оставляют атрибуты без изменений. These text attributes do not affect characters written by the low-level console I/O functions (such as the WriteConsoleOutput or WriteConsoleOutputCharacter function), which either explicitly specify the attributes for each cell that is written or leave the attributes unchanged.
Мы не рекомендуем использовать низкоуровневые функции для изменения атрибутов текста (в том числе атрибутов по умолчанию). Using the low-level functions to manipulate default and specific text attributes is discouraged. Чтобы задать атрибуты текста, используйте последовательности виртуального терминала. It is recommended to use virtual terminal sequences to set text attributes. Дополнительные сведения о предпочтительных последовательностях виртуального терминала см. в документе о классических функциях и виртуальном терминале . More information about preferring virtual terminal sequences can be found in the classic functions versus virtual terminal document.
Атрибуты шрифтов Font Attributes
Функция GetCurrentConsoleFont получает сведения о текущем шрифте консоли. The GetCurrentConsoleFont function retrieves information about the current console font. В структуре CONSOLE_FONT_INFO хранятся такие сведения, как ширина и высота каждого символа в шрифте. The information stored in the CONSOLE_FONT_INFO structure includes the width and height of each character in the font.
Функция GetConsoleFontSize получает данные о размере шрифта, используемые конкретным буфером экрана консоли. The GetConsoleFontSize function retrieves the size of the font used by the specified console screen buffer.
Мы не рекомендуем использовать функции для поиска и изменения данных шрифтов. Using functions to find and manipulate font information is discouraged. Придерживайтесь нейтральности шрифтов в приложениях командной строки, чтобы обеспечить совместимость с другими платформами, а также совместимость со средами размещения, которые разрешают пользователям настраивать шрифты. It is recommended to operate command-line applications in a font neutral manner to ensure cross-platform compatibility as well as compatibility with host environments that allow the user to customize the font. Дополнительные сведения о предпочтениях пользователей и средах размещения (в том числе о терминалах), см. в статье о стратегии развития экосистемы . More information user preferences and host environments including terminals, please see the ecosystem roadmap.