Windows console window size

SetConsoleWindowInfo 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.

Sets the current size and position of a console screen buffer’s window.

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.

bAbsolute [in]
If this parameter is TRUE, the coordinates specify the new upper-left and lower-right corners of the window. If it is FALSE, the coordinates are relative to the current window-corner coordinates.

lpConsoleWindow [in]
A pointer to a SMALL_RECT structure that specifies the new upper-left and lower-right corners of the window.

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

The function fails if the specified window rectangle extends beyond the boundaries of the console screen buffer. This means that the Top and Left members of the lpConsoleWindow rectangle (or the calculated top and left coordinates, if bAbsolute is FALSE) cannot be less than zero. Similarly, the Bottom and Right members (or the calculated bottom and right coordinates) cannot be greater than (screen buffer height – 1) and (screen buffer width – 1), respectively. The function also fails if the Right member (or calculated right coordinate) is less than or equal to the Left member (or calculated left coordinate) or if the Bottom member (or calculated bottom coordinate) is less than or equal to the Top member (or calculated top coordinate).

For consoles with more than one screen buffer, changing the window location for one screen buffer does not affect the window locations of the other screen buffers.

To determine the current size and position of a screen buffer’s window, use the GetConsoleScreenBufferInfo function. This function also returns the maximum size of the window, given the current screen buffer size, the current font size, and the screen size. The GetLargestConsoleWindowSize function returns the maximum window size given the current font and screen sizes, but it does not consider the size of the console screen buffer.

SetConsoleWindowInfo can be used to scroll the contents of the console screen buffer by shifting the position of the window rectangle without changing its size.

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. Set Window Size(Int32, Int32) Метод

Определение

Устанавливает заданные значения высоты и ширины окна консоли. Sets the height and width of the console window to the specified values.

Параметры

Ширина окна консоли измеряется столбцами. The width of the console window measured in columns.

Высота окна консоли измеряется строками. The height of the console window measured in rows.

Исключения

width или height меньше или равно нулю. width or height is less than or equal to zero.

Сумма width и WindowLeft либо сумма height и WindowTop больше или равна MaxValue. width plus WindowLeft or height plus WindowTop is greater than or equal to MaxValue.

Читайте также:  Антивирус при загрузке windows

Значение параметра width или height больше ширины или высоты окна максимально возможной при текущем разрешении и шрифте консоли. width or height is greater than the largest possible window width or height for the current screen resolution and console font.

Пользователь не имеет разрешений на выполнение этого действия. The user does not have permission to perform this action.

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

Текущая операционная система не является системой Windows. The current operating system is not Windows.

Примеры

В этом примере демонстрируется SetWindowSize метод, а WindowWidth также WindowHeight Свойства и. This example demonstrates the SetWindowSize method, and the WindowWidth and WindowHeight properties. Чтобы увидеть полный результат изменения размера окна консоли, необходимо выполнить пример. You must run the example to see the full effect of changing the console window size.

Пример сообщает размерам окна консоли, для которых задано значение 85 столбцов и 43 строк, а затем ожидает нажатия клавиши. The example reports the dimensions of a console window set to 85 columns and 43 rows, then waits for a key to be pressed. При нажатии любой клавиши размеры окна консоли увеличиваются вдвое, выводятся новые измерения, а в примере ожидается еще один нажатие клавиши. When any key is pressed, the dimensions of the console window are halved, the new dimensions are reported, and the example waits for another key press. Наконец, при нажатии любой клавиши окно консоли восстанавливается до исходных измерений, а пример завершается. Finally, when any key is pressed, the console window is restored to its original dimensions and the example terminates.

Размер окна и буфера экрана Window and Screen Buffer Size

Размер буфера экрана выражается в виде координатной сетки, основанной на ячейках символов. The size of a screen buffer is expressed in terms of a coordinate grid based on character cells. Ширина — это число ячеек символов в каждой строке, а высота — число строк. The width is the number of character cells in each row, and the height is the number of rows. Связанный с каждым буфером экрана — это окно, определяющее размер и расположение прямоугольной части буфера экрана консоли, отображаемой в окне консоли. Associated with each screen buffer is a window that determines the size and location of the rectangular portion of the console screen buffer displayed in the console window. Окно буфера экрана определяется с помощью указания координат символьной ячейки в верхней левой и нижней правой ячейках прямоугольника окна. A screen buffer’s window is defined by specifying the character-cell coordinates of the upper left and lower right cells of the window’s rectangle.

В мире виртуальных последовательностей терминалов размер окна и размер буфера экрана фиксируются для одного и того же значения. In the virtual terminal sequences world, the size of the window and the size of the screen buffer are fixed to the same value. Терминал обрабатывает любой регион скроллбакк, который будет эквивалентом консоли с размером буфера экрана, превышающим размер окна. The terminal handles any scrollback region that would be the equivalent of a console with a screen buffer size larger than its window size. Это содержимое принадлежит терминалу и, как правило, больше не является частью области с адресацией. That content belongs to the terminal and is generally no longer a part of the addressable area. Дополнительные сведения см. в статье сравнение классических функций консоли и виртуальных последовательностей терминалов . For more information, please see our comparison of the classic console functions versus virtual terminal sequences .

Буфер экрана может иметь любой размер, ограниченный только объемом доступной памяти. A screen buffer can be any size, limited only by available memory. Размеры окна буфера экрана не могут превышать соответствующие размеры буфера экрана консоли или максимального окна, которое может уместиться на экране на основе текущего размера шрифта (управляется исключительно пользователем). The dimensions of a screen buffer’s window cannot exceed the corresponding dimensions of either the console screen buffer or the maximum window that can fit on the screen based on the current font size (controlled exclusively by the user).

Читайте также:  Windows server evaluation или datacenter

Функция жетконсолескринбуфферинфо возвращает следующие сведения о буфере экрана и его окне: The GetConsoleScreenBufferInfo function returns the following information about a screen buffer and its window:

  • Текущий размер буфера экрана консоли The current size of the console screen buffer
  • Текущее расположение окна The current location of the window
  • Максимальный размер окна, учитывая текущий размер буфера экрана, текущий размер шрифта и размер экрана The maximum size of the window given the current screen buffer size, the current font size, and the screen size

Функция жетларжестконсолевиндовсизе Возвращает максимальный размер окна консоли на основе текущего шрифта и размеров экрана. The GetLargestConsoleWindowSize function returns the maximum size of a console’s window based on the current font and screen sizes. Этот размер отличается от максимального размера окна, возвращенного жетконсолескринбуфферинфо в том случае, если размер буфера экрана консоли не учитывается. This size differs from the maximum window size returned by GetConsoleScreenBufferInfo in that the console screen buffer size is ignored.

Чтобы изменить размер буфера экрана, используйте функцию сетконсолескринбуфферсизе . To change a screen buffer’s size, use the SetConsoleScreenBufferSize function. Эта функция завершается ошибкой, если любое измерение указанного размера меньше, чем соответствующее измерение окна консоли. This function fails if either dimension of the specified size is less than the corresponding dimension of the console’s window.

Чтобы изменить размер или расположение окна буфера экрана, используйте функцию сетконсолевиндовинфо . To change the size or location of a screen buffer’s window, use the SetConsoleWindowInfo function. Эта функция завершается ошибкой, если указанные координаты углового окна превышают пределы буфера экрана консоли или экрана. This function fails if the specified window-corner coordinates exceed the limits of the console screen buffer or the screen. Изменение размера окна активного буфера экрана изменяет размер окна консоли, отображаемого на экране. Changing the window size of the active screen buffer changes the size of the console window displayed on the screen.

Процесс может изменить входной режим консоли, чтобы разрешить входные данные окна, чтобы процесс мог получать входные данные, когда пользователь изменяет размер буфера экрана консоли. A process can change its console’s input mode to enable window input so that the process is able to receive input when the user changes the console screen buffer size. Если приложение включает входные данные окна, оно может использовать жетконсолескринбуфферинфо для извлечения размера окна и буфера экрана при запуске. If an application enables window input, it can use GetConsoleScreenBufferInfo to retrieve window and screen buffer size at startup. Эти сведения можно затем использовать для определения способа отображения данных в окне. This information can then be used to determine the way data is displayed in the window. Если пользователь изменяет размер буфера экрана консоли, приложение может ответить, изменив способ отображения данных. If the user changes the console screen buffer size, the application can respond by changing the way data is displayed. Например, приложение может настроить способ переноса текста в конце строки при каждом изменении количества символов в строке. For example, an application can adjust the way text wraps at the end of the line if the number of characters per row changes. Если приложение не включает входные данные окна, оно должно либо использовать унаследованные размеры окон и буферов экрана, либо задать требуемый размер во время запуска и восстановить унаследованные размеры при выходе. If an application does not enable window input, it must either use the inherited window and screen buffer sizes, or set them to the desired size during startup and restore the inherited sizes at exit. Дополнительные сведения о режиме ввода окна см. в разделе режимы консоли низкого уровня. For additional information about window input mode, see Low-Level Console Modes.

Читайте также:  Русификатор для windows home premium

Window and Screen Buffer Size

The size of a screen buffer is expressed in terms of a coordinate grid based on character cells. The width is the number of character cells in each row, and the height is the number of rows. Associated with each screen buffer is a window that determines the size and location of the rectangular portion of the console screen buffer displayed in the console window. A screen buffer’s window is defined by specifying the character-cell coordinates of the upper left and lower right cells of the window’s rectangle.

In the virtual terminal sequences world, the size of the window and the size of the screen buffer are fixed to the same value. The terminal handles any scrollback region that would be the equivalent of a console with a screen buffer size larger than its window size. That content belongs to the terminal and is generally no longer a part of the addressable area. For more information, please see our comparison of the classic console functions versus virtual terminal sequences.

A screen buffer can be any size, limited only by available memory. The dimensions of a screen buffer’s window cannot exceed the corresponding dimensions of either the console screen buffer or the maximum window that can fit on the screen based on the current font size (controlled exclusively by the user).

The GetConsoleScreenBufferInfo function returns the following information about a screen buffer and its window:

  • The current size of the console screen buffer
  • The current location of the window
  • The maximum size of the window given the current screen buffer size, the current font size, and the screen size

The GetLargestConsoleWindowSize function returns the maximum size of a console’s window based on the current font and screen sizes. This size differs from the maximum window size returned by GetConsoleScreenBufferInfo in that the console screen buffer size is ignored.

To change a screen buffer’s size, use the SetConsoleScreenBufferSize function. This function fails if either dimension of the specified size is less than the corresponding dimension of the console’s window.

To change the size or location of a screen buffer’s window, use the SetConsoleWindowInfo function. This function fails if the specified window-corner coordinates exceed the limits of the console screen buffer or the screen. Changing the window size of the active screen buffer changes the size of the console window displayed on the screen.

A process can change its console’s input mode to enable window input so that the process is able to receive input when the user changes the console screen buffer size. If an application enables window input, it can use GetConsoleScreenBufferInfo to retrieve window and screen buffer size at startup. This information can then be used to determine the way data is displayed in the window. If the user changes the console screen buffer size, the application can respond by changing the way data is displayed. For example, an application can adjust the way text wraps at the end of the line if the number of characters per row changes. If an application does not enable window input, it must either use the inherited window and screen buffer sizes, or set them to the desired size during startup and restore the inherited sizes at exit. For additional information about window input mode, see Low-Level Console Modes.

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