NAME
Win32API::Console - Win32 native Console API
DESCRIPTION
The console is integrated into Windows and offers a comprehensive API that allows character mode applications to interact with the user. In the past, Perl developers could only use the Win32::Console module (usually only ANSI support and some restrictions).
In order to use the classic API calls with maximum compatibility for Windows, this module was created, which uses most of the XS functions of Win32::Console, but also provides additional ones (e.g., for wide char support).
Further details can be found in the source code or directly at MSDN. The API interface was modeled on the classic Windows API, so that the original documentation from Microsoft can be used in most cases.
SUBROUTINES
Many Windows API functions exist in multiple variants that differ by the character encoding they expect. The naming convention typically uses suffixes:
FunctionNameAThis variant expects ANSI strings encoded in the console's current local code page.
Example:
# Text must be an ANSI string encoded in the local code page FunctionNameA("Text");The parameter is passed as a ANSI string.
Note: A-Version uses ANSI and is not recommended for international applications.
FunctionNameWThis variant expects wide strings encoded as
UTF-16LE.Example:
# Text must be a sequence of bytes encoded as UTF-16LE use Encode; FunctionNameW( Encode::encode('UTF-16LE' => "Text") );The parameter is passed as a WCHAR string.
Note: W-Version uses
UTF-16LEand is the quasi standard for Windows applications.FunctionNameThis wrapper decides internally based on the compiler setting and automatically encodes/decodes the Perl string (UTF-8) to/from ANSI or WCHAR using Encode in a call to the A or W variant.
If
UNICODEis enabled, the W version is used.If
UNICODEis disabled, the A version is used.
Example:
# Text must be a Perl string encoded as UTF-8. use utf8; FunctionName("Text");Note: The wrapper provides a compatibility layer, but its behavior depends on the internal XS build configuration of Win32::Console.
Please also refer to the Windows-specific "CAVEATS" section for important details when using these wrapper functions.
AllocConsole
my $scalar | undef = AllocConsole();
AllocConsole creates a new console for the calling process. Useful when running GUI applications that need to output to a console window.
Returns: non-zero on success, undef on failure.
Note: After calling AllocConsole, standard handles (STDIN, STDOUT, STDERR) can be redirected to the new console using "SetStdHandle".
AllocConsoleWithOptions
my $scalar | undef = AllocConsoleWithOptions($mode, $show | undef, \$result);
AllocConsoleWithOptions wraps the Windows API function. It allocates a console with optional window display settings and returns the result code.
$mode: console allocation mode (0 = default, 1 = new window, 2 = no win)$show: optional showWindow flag (e.g.SW_SHOW,SW_HIDE)\$result: result code (ALLOC_CONSOLE_RESULT)
Note: We do not use the ALLOC_CONSOLE_OPTIONS structure. Instead, we use positional parameters. If $show is defined, it is used as a parameter for displaying the console window. For more information, see ShowWindow.
Returns: non-zero success, undef on failure
Use GetLastError() to retrieve extended error information.
Note: We do not return HRESULT, but instead set SetLastError (extracting the Win32 error code if FACILITY_WIN32 flag is set).
AttachConsole
my $scalar | undef = AttachConsole($pid);
AttachConsole attaches the calling process to the console of another process. Useful for redirecting output/input to an existing console window (e.g. from a GUI app).
$pid: process ID of the target console owner
Use ATTACH_PARENT_PROCESS (-1) to attach to the parent process's console.
Returns: non-zero on success, undef on failure.
Note: After attaching, standard handles (STDIN, STDOUT, STDERR) can be used to interact with the attached console.
CloseHandle
my $scalar | undef = CloseHandle($handle);
CloseHandle closes an open console handle (but not only consoles; other object handles such as files or processes can also be closed).
$handle: handle to be closed
Returns: non-zero on success, undef on failure.
CreateConsoleScreenBuffer
my $scalar | undef = CreateConsoleScreenBuffer($access, $shareMode);
CreateConsoleScreenBuffer creates a new console screen buffer. Useful for off-screen rendering or switching between buffers.
$access: desired access (e.g.GENERIC_READ | GENERIC_WRITE)$shareMode: sharing mode (e.g.FILE_SHARE_READ | FILE_SHARE_WRITE)
Returns: handle to the new buffer on success, undef on failure.
Use GetLastError() to retrieve extended error information.
FillConsoleOutputAttribute
my $scalar | undef = FillConsoleOutputAttribute($handle, $attr, $length, \%coord, \$written);
FillConsoleOutputAttribute sets character attributes (e.g. color) in the console buffer.
$handle: Console screen buffer handle$attr: Attribute value (e.g.FOREGROUND_RED | BACKGROUND_BLUE)$length: Number of cells to fill\%coord: Starting coordinate ("COORD" structure)\$written: Number of attributes written
Returns: non-zero on success, undef on failure.
FillConsoleOutputCharacter
my $scalar | undef = FillConsoleOutputCharacter($handle, $char, $length, \%coord, \$written);
FillConsoleOutputCharacter writes a repeated character to the console buffer.
$handle: Console screen buffer handle$char: Character to write$length: Number of cells to write the character\%coord: Starting coordinate ("COORD" structure)\$written: Number of characters written
Returns: non-zero on success, undef on failure.
FillConsoleOutputCharacterA
my $scalar | undef = FillConsoleOutputCharacterA($handle, $char, $length, \%coord, \$written);
FillConsoleOutputCharacterW
my $scalar | undef = FillConsoleOutputCharacterW($handle, $char, $length, \%coord, \$written);
FlushConsoleInputBuffer
my $scalar | undef = FlushConsoleInputBuffer($handle);
FlushConsoleInputBuffer clears all pending input events from the console input buffer.
$handle: handle to the console input buffer
Returns: non-zero on success, undef on failure.
FreeConsole
my $scalar | undef = FreeConsole();
FreeConsole detaches the calling process from its current console. Useful when a process no longer needs console I/O or wants to release the console.
Returns: non-zero on success, undef on failure.
Note: After calling FreeConsole, STDIN, STDOUT, and STDERR are no longer valid unless a new console is allocated (via "AllocConsole") or attached (via "AttachConsole").
GenerateConsoleCtrlEvent
my $scalar | undef = GenerateConsoleCtrlEvent($event, $groupId);
GenerateConsoleCtrlEvent sends a CTRL+C or CTRL+BREAK signal to a process group.
$event:CTRL_C_EVENTorCTRL_BREAK_EVENT$groupId: Process group ID to receive the signal
Returns: non-zero on success, undef on failure.
GetConsoleCP
my $codepage = GetConsoleCP();
GetConsoleCP retrieves the input code page used by the console.
Returns: code page identifier (e.g. 65001 for UTF-8).
Use GetLastError() to retrieve extended error information.
GetConsoleCursorInfo
my $scalar | undef = GetConsoleCursorInfo($handle, \%info);
GetConsoleCursorInfo retrieves the size and visibility of the console cursor.
$handle: Console screen buffer handle\%info: Hash reference to receive a "CONSOLE_CURSOR_INFO" structure
Returns: non-zero on success, undef on failure.
GetConsoleDisplayMode
my $scalar | undef = GetConsoleDisplayMode(\$flags);
GetConsoleDisplayMode retrieves the display mode of the current console.
\$flags: Reference to a scalar receiving the display mode
Returns: non-zero on success, undef on failure.
Note: Since ~ Windows 10, the function does not deliver correct results. If Win32::GuiTest is available (and EMULATE_DISPLAY_MODE is true), we try to emulate the function by determining the mode based on the ratio of window size to screen size.
GetConsoleFontSize
my \%coord | undef = GetConsoleFontSize($handle, $index);
GetConsoleFontSize retrieves the size of the font used by the console.
$handle: Handle to the console output buffer$index: Index of the font (usually from "GetCurrentConsoleFont")
Returns: COORD structure with width and height of the font, undef on failure.
Use GetLastError() to retrieve extended error information.
Note: GetConsoleFontSize() returns the size (0,16) in Windows-Terminal. See: https://github.com/microsoft/terminal/issues/6395
We therefore calculate the font size based on the pixels of the window client width and height of the console area using GetClientRect and "GetConsoleScreenBufferInfo" (prerequisite that EMULATE_FONT_SIZE is enabled).
GetConsoleMode
my $scalar | undef = GetConsoleMode($handle, \$mode);
GetConsoleMode retrieves the current input or output mode of a console handle.
$handle: Handle to console input or output\$mode: Reference to a scalar receiving the mode flags
Returns: non-zero on success, undef on failure.
GetConsoleOriginalTitle
my $num | undef = GetConsoleOriginalTitle(\$buffer, $size);
GetConsoleOriginalTitle retrieves the original title of the console window.
\$buffer: Reference to a buffer receiving the title string$size: Size of the buffer in characters
Returns: number of characters copied, undef on failure.
Use GetLastError() to retrieve extended error information.
GetConsoleOriginalTitleA
my $num | undef = GetConsoleOriginalTitleA($handle, $index);
GetConsoleOriginalTitleW
my $num | undef = GetConsoleOriginalTitleW($handle, $index);
GetConsoleOutputCP
my $codepage = GetConsoleOutputCP();
GetConsoleOutputCP retrieves the output code page used by the console.
Returns: code page identifier (e.g. 65001 for UTF-8).
Use GetLastError() to retrieve extended error information.
GetConsoleScreenBufferInfo
my $scalar | undef = GetConsoleScreenBufferInfo($handle, \%info);
GetConsoleScreenBufferInfo retrieves information about the console screen buffer.
$handle: Handle to the console screen buffer\%info: Reference to "CONSOLE_SCREEN_BUFFER_INFO" structure
"CONSOLE_SCREEN_BUFFER_INFO" structure used by GetConsoleScreenBufferInfo to receive the information about a console screen buffer:
{dwSize} Specifies the size of the screen buffer in character
columns and rows (COORD structure).
{dwCursorPosition} Indicates the current position of the cursor within
the screen buffer (COORD structure).
{wAttributes} Holds the current text attributes (like foreground and
background colors).
{srWindow} Defines the coordinates of the visible window within
the screen buffer (SMALL_RECT structure).
{dwMaximumWindowSize} Specifies the maximum size the console window can be,
based on the current font and screen size (COORD).
Return:
Returns: non-zero on success, undef on failure.
GetConsoleScreenBufferInfoEx
my $scalar | undef = GetConsoleScreenBufferInfoEx($handle, \%infoEx);
GetConsoleScreenBufferInfoEx retrieves extended information about a console screen buffer.
$handle: Handle to the console output buffer\%infoEx: "CONSOLE_SCREEN_BUFFER_INFOEX" to receive the information
Note: $infoEx->{cbSize} is set by this function and therefore does not need to be passed.
Returns: non-zero on success, undef on failure.
GetConsoleTitle
my $num | undef = GetConsoleTitle(\$buffer, $size);
GetConsoleTitle retrieves the title of the current console window.
\$buffer: Reference to a buffer receiving the title string$size: Size of the buffer in characters
Returns: number of characters copied, undef on failure.
Use GetLastError() to retrieve extended error information.
Note: The buffer for the ANSI version contains an empty string if the specified length is greater than 1024, due to the limitation of the underlying XS function of Win32::Console.
GetConsoleTitleA
my $num | undef = GetConsoleTitleA(\$buffer, $size);
GetConsoleTitleW
my $num | undef = GetConsoleTitleW(\$buffer, $size);
GetConsoleWindow
my $hwnd | undef = GetConsoleWindow();
GetConsoleWindow retrieves the window handle used by the console associated with the calling process.
Returns: handle to the window used by the console associated with
the calling process or undef if there is no such associated console.
GetCurrentConsoleFont
my $scalar | undef = GetCurrentConsoleFont($handle, $max, \%info);
GetCurrentConsoleFont retrieves information about the current console font.
$handle: Handle to the console output buffer$max: TRUE to retrieve maximum font size, FALSE for current\%info: "CONSOLE_FONT_INFO" HashRef to receive the font information
Returns: non-zero on success, undef on failure.
GetCurrentConsoleFontEx
my $scalar | undef = GetCurrentConsoleFontEx($handle, $max, \%info);
GetCurrentConsoleFontEx retrieves extended information about the current console font.
$handle: Handle to the console output buffer$max: TRUE to retrieve maximum font size, FALSE for current\%info: "CONSOLE_FONT_INFOEX" HashRef to receive the information
Note: $info->{cbSize} is set by this function and therefore does not need to be passed.
Returns: non-zero on success, undef on failure.
Note: GetCurrentConsoleFontEx returns the size (0,16) in Windows-Terminal. See: "GetConsoleFontSize" for further information.
GetLargestConsoleWindowSize
my \%coord | undef = GetLargestConsoleWindowSize($handle);
GetLargestConsoleWindowSize returns the largest possible size for the console window.
$handle: handle to the console screen buffer
Returns: COORD structure with maximum width and height, undef on failure.
Use GetLastError() to retrieve extended error information.
GetNumberOfConsoleFonts
my $num | undef = GetNumberOfConsoleFonts();
To identify the index of a font, call the GetCurrentConsoleFont function.
Returns: Number of console fonts on success, undef on failure.
Use GetLastError() to retrieve extended error information.
Notes: GetCurrentConsoleFont returns the size (0,16) in Windows-Terminal. See: "GetConsoleFontSize" for further information. This function is not documented and may not work with current Windows versions.
GetNumberOfConsoleInputEvents
my $scalar | undef = GetNumberOfConsoleInputEvents($handle, \$count);
GetNumberOfConsoleInputEvents retrieves the number of unread input events in the buffer.
$handle: Handle to the console input buffer\$count: Reference to variable receiving the count
Returns: non-zero on success, undef on failure.
GetStdHandle
my $handle = GetStdHandle($id);
GetStdHandle retrieves a handle to the standard input, output, or error device.
$id: identifier (e.g.STD_INPUT_HANDLE, see ":STD_HANDLE_")
Returns: handle on success, INVALID_HANDLE_VALUE on failure.
Use GetLastError() to retrieve extended error information.
PeekConsoleInput
my $scalar | undef = PeekConsoleInput($handle, \%buffer);
PeekConsoleInput reads input events from the console input buffer without removing them.
$handle: Handle to the console input buffer\%buffer: Reference to a INPUT_RECORD structure
INPUT_RECORD structure used by PeekConsoleInput and to represent a single input event. See "ReadConsoleInput" for the complete description of INPUT_RECORD.
Returns: nonzero or "0 but true" on success, undef on failure.
Note: PeekConsoleInput returns 0 but true if the input buffer is empty.
PeekConsoleInputA
my $scalar | undef = PeekConsoleInputA($handle, \%buffer);
PeekConsoleInputW
my $scalar | undef = PeekConsoleInputW($handle, \%buffer);
ReadConsole
my $scalar | undef = ReadConsole($handle, \$buffer, $length, \$read, | \%control | undef);
ReadConsole reads characters from the console input buffer.
$handle: Handle to the console input buffer\$buffer: Reference to buffer receiving the input$length: Number of characters to read\$read: Reference to number of characters actually read\%control: Optional HashRef ("CONSOLE_READCONSOLE_CONTROL" structure)
Returns: non-zero on success, undef on failure.
ReadConsoleA
my $scalar | undef = ReadConsoleA($handle, \$buffer, $length, \$read, | undef);
ReadConsoleInput
my $scalar | undef = ReadConsoleInput($handle, \%buffer);
ReadConsoleInput reads input records (keyboard, mouse, buffer-resize, etc.) from the console input buffer. It is useful for handling low-level console input events in real-time.
$handle: Handle to the console input buffer\%buffer: HashRef that receives a INPUT_RECORD structure
INPUT_RECORD structure used by ReadConsoleInput to represent a single input event. The structure is a union of different event types, distinguished by the {EventType} field.
{EventType} Specifies the type of the input event. Possible values:
0x0001: KEY_EVENT
0x0002: MOUSE_EVENT
0x0004: WINDOW_BUFFER_SIZE_EVENT
0x0008: MENU_EVENT
0x0010: FOCUS_EVENT
{Event} A I<union> of the following structures, depending on {EventType}:
KEY_EVENT_RECORD KeyEvent
MOUSE_EVENT_RECORD MouseEvent
WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent
MENU_EVENT_RECORD MenuEvent
FOCUS_EVENT_RECORD FocusEvent
KEY_EVENT_RECORD structure used when {EventType} == KEY_EVENT (0x0001). Represents a keyboard event (key press or release).
{bKeyDown} TRUE if the key is being pressed, FALSE if released.
{wRepeatCount} Number of times the keystroke is repeated due to key
being held down.
{wVirtualKeyCode} Virtual-key code of the key (e.g. VK_RETURN, VK_ESCAPE).
{wVirtualScanCode} Hardware scan code of the key.
{uChar} The character generated by the key press.
{dwControlKeyState} Bitmask indicating the state of control keys (SHIFT,
CTRL, ALT, CAPSLOCK, etc.)
MOUSE_EVENT_RECORD structure used when {EventType} == MOUSE_EVENT (0x0002). Represents a mouse event in the console window.
{dwMousePosition} X and Y coordinates of the mouse cursor in the console
screen buffer.
{dwButtonState} Bitmask indicating which mouse buttons are pressed.
e.g. FROM_LEFT_1ST_BUTTON_PRESSED
{dwControlKeyState} Bitmask indicating the state of control keys during
the mouse event.
{dwEventFlags} Indicates the type of mouse event:
0x0001: MOUSE_MOVED
0x0002: DOUBLE_CLICK
0x0004: MOUSE_WHEELED
0x0008: MOUSE_HWHEELED
WINDOW_BUFFER_SIZE_RECORD structure used when {EventType} == WINDOW_BUFFER_SIZE_EVENT (0x0004). Represents a change in the size of the console screen buffer.
{dwSize} New size of the screen buffer (width and height).
MENU_EVENT_RECORD structure used when {EventType} == MENU_EVENT (0x0008). Represents a menu event in the console (rarely used in modern applications).
{dwCommandId} Identifier of the command selected from a system menu.
Typically used in legacy console applications with system
menus.
FOCUS_EVENT_RECORD structure used when {EventType} == FOCUS_EVENT (0x0010). Indicates a change in focus to or from the console window.
{bSetFocus} TRUE if the console window has gained focus,
FALSE if it has lost focus.
Return:
Returns: non-zero on success, undef on failure.
ReadConsoleInputA
my $scalar | undef = ReadConsoleInputA($handle, \%buffer);
ReadConsoleInputW
my $scalar | undef = ReadConsoleInputW($handle, \%buffer);
ReadConsoleOutput
my $scalar | undef = ReadConsoleOutput($handle, \$buffer, \%size, \%coord, \%region);
ReadConsoleOutput reads character and attribute data from the console screen buffer.
$handle: Handle to the console screen buffer\$buffer: Reference to a packed string (of CHAR_INFO's)\%size: Size of$buffer("COORD" hash as width and height)\%coord: Coordinates ("COORD") in$bufferto start reading from\%region: "SMALL_RECT" hash defining the screen region to read
Returns: non-zero on success, undef on failure.
Note: If successful, $buffer returns a packed string containing CHAR_INFO's - characters (S) and attributes (S) - and %region returns the rectangle actually used.
ReadConsoleOutputA
my $scalar | undef = ReadConsoleOutputA($handle, \$buffer, \%size, \%coord, \%region);
ReadConsoleOutputW
my $scalar | undef = ReadConsoleOutputW($handle, \$buffer, \%size, \%coord, \%region);
ReadConsoleOutputAttribute
my $scalar | undef = ReadConsoleOutputAttribute($handle, \$buffer, $length, \%coord, \$read);
ReadConsoleOutputAttribute reads character attributes from the console screen buffer.
$handle: Handle to the console screen buffer\$buffer: Reference to a packed string (S*) receiving the attributes$length: Number of attributes to read\%coord: Coordinates to start reading from ("COORD" hash)\$read: Reference to number of attributes read
Returns: non-zero on success, undef on failure.
Note: If successful, $buffer returns the attributes in the form of a packed string (S*), and $read returns the number of attributes.
The Win32::Console XS function has some limitations: the maximum supported data length is 80*999. In addition, the return value only reflects the color attributes (no DCBS support).
ReadConsoleOutputCharacter
my $scalar | undef = ReadConsoleOutputCharacter($handle, \$buffer, $length, \%coord, \$read);
ReadConsoleOutputCharacter reads characters from the console screen buffer.
$handle: Handle to the console screen buffer\$buffer: Reference to buffer receiving characters$length: Number of characters to read\%coord: Coordinates to start reading from ("COORD" hash)\$read: Reference to number of attributes read
Returns: non-zero on success, undef on failure.
ReadConsoleOutputCharacterA
my $scalar | undef = ReadConsoleOutputCharacterA($handle, \$buffer, $length, \%coord, \$read);
ReadConsoleOutputCharacterW
my $scalar | undef = ReadConsoleOutputCharacterW($handle, \$buffer, $length, \%coord, \$read);
ScrollConsoleScreenBuffer
my $scalar | undef = ScrollConsoleScreenBuffer($handle, \%scrollRect, \%clipRect | undef, \%destCoord, \%fill);
ScrollConsoleScreenBuffer scrolls a region of the console screen buffer.
$handle: Handle to the console screen buffer\%scrollRect: "SMALL_RECT" structure defining the region to scroll\%clipRect: Optional clipping rectangle ("SMALL_RECT" orundef)\%destCoord: Destination coordinate ("COORD" struct)\%fill: "CHAR_INFO" structure used to fill emptied space
Returns: non-zero on success, undef on failure.
ScrollConsoleScreenBufferA
my $scalar | undef = ScrollConsoleScreenBufferA($handle, \%scrollRect, \%clipRect | undef, \%destCoord, \%fill);
ScrollConsoleScreenBufferW
my $scalar | undef = ScrollConsoleScreenBufferW($handle, \%scrollRect, \%clipRect | undef, \%destCoord, \%fill);
SetConsoleActiveScreenBuffer
my $scalar | undef = SetConsoleActiveScreenBuffer($handle);
SetConsoleActiveScreenBuffer sets the specified screen buffer as the active one.
$handle: Handle to the screen buffer to activate
Returns: non-zero on success, undef on failure.
SetConsoleCP
my $scalar | undef = SetConsoleCP($codepage);
SetConsoleCP sets the input code page used by the console.
$codepage: Code page identifier (e.g.65001for UTF-8)
Returns: non-zero on success, undef on failure.
SetConsoleCtrlHandler
my $scalar | undef = SetConsoleCtrlHandler(\&handler | undef, $add);
SetConsoleCtrlHandler adds or removes an user-defined handler for console control events.
\&handler: Code reference to a handler function orundefwhen remove$add: TRUE to add, FALSE to remove
A control signal is passed to the handler as a parameter. If the function handles the control signal, TRUE should be returned. If FALSE is returned, the next handler function in the list of handlers for this process is used.
Returns: non-zero on success, undef on failure.
Note: We emulate this function using SIGINT and SIGBREAK, since Perl itself has installed a handler. Currently, only the CTRL_C_EVENT and CTRL_BREAK_EVENT control signals are supported.
SetConsoleCursorInfo
my $scalar | undef = SetConsoleCursorInfo($handle, \%info);
SetConsoleCursorInfo sets the size and visibility of the console cursor.
$handle: Handle to the console screen buffer\%info: Reference to a hash ("CONSOLE_CURSOR_INFO" structure)
Returns: non-zero on success, undef on failure.
SetConsoleCursorPosition
my $scalar | undef = SetConsoleCursorPosition($handle, \%coord);
SetConsoleCursorPosition moves the cursor to a specified location in the console screen buffer.
$handle: Handle to the console screen buffer\%coord: "COORD" structure specifying the new cursor position
Returns: non-zero on success, undef on failure.
SetConsoleDisplayMode
my $scalar | undef = SetConsoleDisplayMode($handle, $flags, \%coord);
SetConsoleDisplayMode sets the display mode of the specified console screen buffer.
$handle: Handle to the console screen buffer$flags: The display mode of the console\%coord: "COORD" specifying the new dimensions of the screen buffer
Returns: non-zero on success, undef on failure.
Note: If the function is no longer supported by the operating system, GetLastError returns 120. If Win32::GuiTest is available, we attempt to emulate the behavior of the API function using the Alt+Enter key combination. See: https://github.com/microsoft/terminal/issues/14885
SetConsoleIcon
my $scalar | undef = SetConsoleIcon($iconFile);
SetConsoleIcon sets the icon for the console window.
$iconFile: file name to an icon file
Returns: non-zero on success, undef on failure.
Note: Not available in all Windows versions.
SetConsoleMode
my $scalar | undef = SetConsoleMode($handle, $mode);
SetConsoleMode sets the input or output mode of a console handle.
$handle: Handle to console input or output$mode: Mode flags (e.g.ENABLE_ECHO_INPUT,ENABLE_LINE_INPUT)
Returns: non-zero on success, undef on failure.
SetConsoleOutputCP
my $scalar | undef = SetConsoleOutputCP($codepage);
SetConsoleOutputCP sets the output code page used by the console.
$codepage: Code page identifier (e.g.65001for UTF-8)
Returns: non-zero on success, undef on failure.
SetConsoleScreenBufferInfoEx
my $scalar | undef = SetConsoleScreenBufferInfoEx($handle, \%infoEx);
SetConsoleScreenBufferInfoEx retrieves extended information about a console screen buffer.
$handle: Handle to the console output buffer\%infoEx: "CONSOLE_SCREEN_BUFFER_INFOEX" for setting the information
Note: $infoEx->{cbSize} is set by this function and can be 0.
Returns: non-zero on success, undef on failure.
SetConsoleScreenBufferSize
my \%coord | undef = SetConsoleScreenBufferSize($handle, \%size);
SetConsoleScreenBufferSize sets the size of the console screen buffer.
$handle: Handle to the console screen buffer\%size: "COORD" structure specifying new width and height
Returns: non-zero on success, undef on failure.
SetConsoleTextAttribute
my \%coord | undef = SetConsoleTextAttribute($handle, $attributes);
SetConsoleTextAttribute sets the text attributes (e.g. color) for characters written to the console.
$handle: Handle to the console screen buffer$attributes: Attribute flags (e.g.FOREGROUND_RED | BACKGROUND_BLUE)
Returns: non-zero on success, undef on failure.
SetConsoleTitle
my $scalar | undef = SetConsoleTitle($title);
SetConsoleTitle sets the title of the console window.
$title: String to be displayed in the console window title bar
Returns: non-zero on success, undef on failure.
SetConsoleTitleA
my $scalar | undef = SetConsoleTitleA($title);
SetConsoleTitleW
my $scalar | undef = SetConsoleTitleW($title);
SetConsoleWindowInfo
my \%coord | undef = SetConsoleWindowInfo($handle, $absolute, \%rect);
SetConsoleWindowInfo sets the size and position of the console window.
$handle: Handle to the console screen buffer$absolute: TRUE for absolute coordinates, FALSE for relative\%rect: "SMALL_RECT" structure defining the new window size
Returns: non-zero on success, undef on failure.
SetCurrentConsoleFontEx
my $scalar | undef = SetCurrentConsoleFontEx($handle, $max, \%info);
SetCurrentConsoleFontEx sets the font used by the console.
$handle: Handle to the console output buffer$max: TRUE to retrieve maximum font size, FALSE for current\%info: Hash reference to a "CONSOLE_FONT_INFOEX" structure
Note: $info->{cbSize} is set by this function and can be 0.
Returns: non-zero on success, undef on failure.
SetStdHandle
my $handle | undef = SetStdHandle($id, $handle);
SetStdHandle sets the handle for standard input, output, or error.
$id: Identifier (e.g.STD_INPUT_HANDLE,STD_OUTPUT_HANDLE)$handle: New handle to assign
Returns: non-zero on success, undef on failure.
WriteConsole
my $scalar | undef = WriteConsole($handle, $buffer, \$written);
WriteConsole writes a string of characters to the console output buffer.
$handle: Handle to the console output buffer$buffer: String to write\$written: Reference to number of characters actually written
Returns: non-zero on success, undef on failure.
WriteConsoleA
my $scalar | undef = WriteConsoleA($handle, $buffer, \$written);
WriteConsoleW
my $scalar | undef = WriteConsoleW($handle, $buffer, \$written);
WriteConsoleInput
my $scalar | undef = WriteConsoleInput($handle, \%record);
WriteConsoleInput writes input records to the console input buffer.
$handle: Handle to the console input buffer\%record: Hash reference to a INPUT_RECORD structure
Returns: non-zero on success, undef on failure.
WriteConsoleInputA
my $scalar | undef = WriteConsoleInputA($handle, \%record);
WriteConsoleInputW
my $scalar | undef = WriteConsoleInputW($handle, \%record);
WriteConsoleOutput
my $scalar | undef = WriteConsoleOutput($handle, $buffer, \%size, \%coord, \%region);
WriteConsoleOutput function writes a block of character and attribute data to a specified rectangular region of a console screen buffer. It is useful for rendering formatted text directly to the console.
$handle: Handle to the console screen buffer$buffer: Packed string of CHAR_INFO's - chars (S) and attributes (S)\%size: Size of CHAR_INFO's' (COORD as width and height)\%coord: Coordinates in the buffer to start writing ("COORD" hash)\%region: "SMALL_RECT" defining the target region in the screen buffer
Returns: non-zero on success, undef on failure.
Note: If successful, %region returns the actual rectangle that was used.
WriteConsoleOutputA
my $scalar | undef = WriteConsoleOutputA($handle, $buffer, \%size, \%coord, \%region);
WriteConsoleOutputW
my $scalar | undef = WriteConsoleOutputW($handle, $buffer, \%size, \%coord, \%region);
WriteConsoleOutputAttribute
my $scalar | undef = WriteConsoleOutputAttribute($handle, $buffer, \%coord, \$written);
WriteConsoleOutputAttribute writes character attributes to the console screen buffer.
$handle: Handle to the console screen buffer$buffer: Packed string of attributes (S*)\%coord: Starting coordinate ("COORD" structure)\$written: Reference to number of attributes written
Returns: non-zero on success, undef on failure.
Note: The Win32::Console XS function has some limitations: the maximum supported data length is 80*999. Furthermore, only the lower byte of the attribute (the color component) is processed (no DCBS support).
WriteConsoleOutputCharacter
my $scalar | undef = WriteConsoleOutputCharacter($handle, $buffer, \%coord, \$written);
WriteConsoleOutputCharacter writes characters to the console screen buffer.
$handle: Handle to the console screen buffer$buffer: String of characters\%coord: Starting coordinate ("COORD" structure)\$written: Reference to number of attributes written
Returns: non-zero on success, undef on failure.
WriteConsoleOutputCharacterA
my $scalar | undef = WriteConsoleOutputCharacterA($handle, $buffer, \%coord, \$written);
WriteConsoleOutputCharacterW
my $scalar | undef = WriteConsoleOutputCharacterW($handle, $buffer, \%coord, \$written);
STRUCTURES
CHAR_INFO
my $hashref | undef = CHAR_INFO( | @array | \%hashref);
Usage:
my \%hashref = CHAR_INFO();
my \%hashref = CHAR_INFO($char, $attributes) // die;
my \%hashref = CHAR_INFO({
Char => $char,
Attributes => $attributes,
}) // die;
CHAR_INFO::list
my @array = CHAR_INFO::list(\%hashref);
CHAR_INFO::pack
my $scalar = CHAR_INFO::pack(\%hashref);
CHAR_INFO::unpack
my @array = CHAR_INFO::unpack($scalar);
CONSOLE_CURSOR_INFO
my $hashref | undef = CONSOLE_CURSOR_INFO( | @array | \%hashref);
Usage:
my \%hashref = CONSOLE_CURSOR_INFO();
my \%hashref = CONSOLE_CURSOR_INFO($size, $visible) // die;
my \%hashref = CONSOLE_CURSOR_INFO({
dwSize => $size,
bVisible => $visible,
}) // die;
CONSOLE_FONT_INFO
my $hashref | undef = CONSOLE_FONT_INFO( | @array | \%hashref);
Usage:
my \%hashref = CONSOLE_FONT_INFO();
my @fontSize = ($fontSizeX, $fontSizeY);
my \%hashref = CONSOLE_FONT_INFO($index, @fontSize) // die;
my \%hashref = CONSOLE_FONT_INFO({
nFont => $index,
dwFontSize => COORD(@fontSize),
}) // die;
CONSOLE_FONT_INFOEX
my $hashref | undef = CONSOLE_FONT_INFOEX( | @array | \%hashref);
Usage:
my \%hashref = CONSOLE_FONT_INFOEX();
my @fontSize = ($fontSizeX, $fontSizeY);
my \%hashref = CONSOLE_FONT_INFOEX(
CONSOLE_FONT_INFOEX_SIZE,
$index,
@fontSize,
$pitch,
$weight,
$string,
) // die;
my \%hashref = CONSOLE_FONT_INFOEX({
cbSize => CONSOLE_FONT_INFOEX_SIZE,
nFont => $index,
dwFontSize => COORD(@fontSize),
FontFamily => $pitch,
FontWeight => $weight,
FaceName => $string,
}) // die;
CONSOLE_READCONSOLE_CONTROL
my $hashref | undef = CONSOLE_READCONSOLE_CONTROL( | @array | \%hashref);
Usage:
my \%hashref = CONSOLE_READCONSOLE_CONTROL();
my \%hashref = CONSOLE_READCONSOLE_CONTROL($len, $n, $mask, $state) // die;
my \%hashref = CONSOLE_READCONSOLE_CONTROL({
nLength => $len,
nInitialChars => $n,
dwCtrlWakeupMask => $mask,
dwControlKeyState => $state,
}) // die;
CONSOLE_SCREEN_BUFFER_INFO
my $hashref | undef = CONSOLE_SCREEN_BUFFER_INFO( | @array | \%hashref);
Usage:
my \%hashref = CONSOLE_SCREEN_BUFFER_INFO();
my @size = ($sizeX, $sizeY);
my @cursor = ($cursorX, $cursorY);
my @win_rect = ($left, $top, $right, $bottom);
my @max_size = ($maxX, $maxY);
my \%hashref = CONSOLE_SCREEN_BUFFER_INFO(
@size,
@cursor,
$attr,
@win_rect,
@max_size,
) // die;
my \%hashref = CONSOLE_SCREEN_BUFFER_INFO({
dwSize => COORD(@size),
dwCursorPosition => COORD(@cursor),
wAttributes => $attr,
srWindow => SMALL_RECT(@win_rect),
dwMaximumWindowSize => COORD(@max_size)
}) // die;
CONSOLE_SCREEN_BUFFER_INFOEX
my $hashref | undef = CONSOLE_SCREEN_BUFFER_INFOEX( | @array | \%hashref);
Usage:
my \%hashref = CONSOLE_SCREEN_BUFFER_INFOEX();
my @size = ($sizeX, $sizeY);
my @cursor = ($cursorX, $cursorY);
my @win_rect = ($left, $top, $right, $bottom);
my @max_size = ($maxX, $maxY);
my @palette = (0..15);
my \%hashref = CONSOLE_SCREEN_BUFFER_INFOEX(
CONSOLE_SCREEN_BUFFER_INFOEX_SIZE,
@size,
@cursor,
$attr,
@win_rect,
@max_size,
$pop_attr,
$fullscreen,
@palette,
) // die;
my \%hashref = CONSOLE_SCREEN_BUFFER_INFOEX({
cbSize => CONSOLE_SCREEN_BUFFER_INFOEX_SIZE,
dwSize => COORD(@size),
dwCursorPosition => COORD(@cursor),
wAttributes => $attr,
srWindow => SMALL_RECT(@win_rect),
dwMaximumWindowSize => COORD(@max_size)
wPopupAttributes => $pop_attr,
bFullscreenSupported => $fullscreen,
ColorTable => [ @palette ],
}) // die;
COORD
my $hashref | undef = COORD( | @array | \%hashref);
Usage:
my \%hashref = COORD();
my \%hashref = COORD($x, $y) // die;
my \%hashref = COORD({X => $x, Y = $y}) // die;
COORD::list
my @array = COORD::list(\%hashref);
COORD::pack
my $scalar = COORD::pack(\%hashref);
COORD::unpack
my @array = COORD::unpack($scalar);
SMALL_RECT
my $hashref | undef = SMALL_RECT( | @array | \%hashref);
Usage:
my \%hashref = SMALL_RECT();
my \%hashref = SMALL_RECT(
$left,
$top,
$right,
$bottom,
) // die;
my \%hashref = SMALL_RECT({
Left => $left,
Top => $top,
Right => $right,
Bottom => $bottom,
}) // die;
SMALL_RECT::list
my @array = SMALL_RECT::list(\%hashref);
SMALL_RECT::pack
my $scalar = SMALL_RECT::pack(\%hashref);
SMALL_RECT::unpack
my @array = SMALL_RECT::unpack($scalar);
HELPER
Encode::ANSI::decode
my $str = Encode::ANSI::decode($ansi, | $codepage);
Decode the ANSI string into a Perl string using the system code page or $codepage, if specified.
Note: If the code page is CP_UTF8, no conversion takes place, but the UTF8 flag may be set.
Encode::ANSI::encode
my $ansi = Encode::ANSI::encode($str, | $codepage);
Use the default system code page if none is specified, and encode the character string only if the target $codepage is not CP_UTF8.
First convert the UTF-8 string to a UTF-16LE wide string, then convert the UTF-16LE wide string to a multibyte string using the target $codepage and return the encoded multibyte (ANSI) version.
Note: Only converts if $str has UTF-8 characters, otherwise it is already ANSI compatible. The returned string does not have the UTF8 flag set.
GetOSVersion
my $scalar | @array = GetOSVersion();
GetOSVersion retrieves information about the current Windows operating system. This Version should also work for Version > 6.2.
Returns a list containing:
[0] OS description string (e.g. "Microsoft Windows 10")
[1] Major version number (e.g. 10)
[2] Minor version number (e.g. 0)
[3] Build number (e.g. 19041)
[4] Platform ID (e.g. 2 for Win32_NT)
On Windows NT 4 SP6 and later this function returns the following additional
values:
[5] Service Pack Major version number
[6] Service Pack Minor version number
[7] Suite Mask
[8] Product Type
In a scalar context, it returns only the Platform ID [4].
EXPORTS
Nothing is exported by default. The following tags can be used to have large sets of symbols exported.
:Func
The basic function names.
:FuncA
The ANSI-specific functions. Each of these is just the same as the version without the trailing "A" when Win32API::Console::UNICODE is FALSE.
FillConsoleOutputCharacterA
GetConsoleOriginalTitleA
GetConsoleTitleA
PeekConsoleInputA
ReadConsoleA
ReadConsoleInputA
ReadConsoleOutputA
ReadConsoleOutputCharacterA
ScrollConsoleScreenBufferA
SetConsoleTitleA
WriteConsoleA
WriteConsoleInputA
WriteConsoleOutputA
WriteConsoleOutputCharacterA
:FuncW
The wide-character-specific (Unicode) functions. Each of these is just the same as the version without the trailing "W" when Win32API::Console::UNICODE is TRUE.
FillConsoleOutputCharacterW
GetConsoleOriginalTitleW
GetConsoleTitleW
PeekConsoleInputW
ReadConsoleW
ReadConsoleInputW
ReadConsoleOutputW
ReadConsoleOutputCharacterW
ScrollConsoleScreenBufferW
SetConsoleTitleW
WriteConsoleW
WriteConsoleInputW
WriteConsoleOutputW
WriteConsoleOutputCharacterW
:Misc
GetOSVersion
ATTACH_PARENT_PROCESS
CONSOLE_TEXTMODE_BUFFER
INVALID_HANDLE_VALUE
:Struct
The following structures ("STRUCTURES") are used to access a console.
CHAR_INFO
CONSOLE_CURSOR_INFO
CONSOLE_FONT_INFO
CONSOLE_FONT_INFOEX
CONSOLE_READCONSOLE_CONTROL
CONSOLE_SCREEN_BUFFER_INFO
CONSOLE_SCREEN_BUFFER_INFOEX
COORD
SMALL_RECT
:ALLOC_CONSOLE_
Constants for "AttachConsole", "AllocConsoleWithOptions" and "AllocConsole".
ALLOC_CONSOLE_MODE_DEFAULT
ALLOC_CONSOLE_MODE_NEW_WINDOW
ALLOC_CONSOLE_MODE_NO_WINDOW
ALLOC_CONSOLE_RESULT_NO_CONSOLE
ALLOC_CONSOLE_RESULT_NEW_CONSOLE
ALLOC_CONSOLE_RESULT_EXISTING_CONSOLE
:BACKGROUND_
Constants for "GetConsoleScreenBufferInfo", "SetConsoleTextAttribute", "ReadConsoleOutput", "WriteConsoleOutput", "ReadConsoleOutputAttribute", "WriteConsoleOutputAttribute" and "FillConsoleOutputAttribute".
BACKGROUND_BLUE
BACKGROUND_GREEN
BACKGROUND_RED
BACKGROUND_INTENSITY
:BUTTON_PRESSED_
Constants for "PeekConsoleInput", "ReadConsoleInput" and "WriteConsoleInput".
FROM_LEFT_1ST_BUTTON_PRESSED
FROM_LEFT_2ND_BUTTON_PRESSED
FROM_LEFT_3RD_BUTTON_PRESSED
FROM_LEFT_4TH_BUTTON_PRESSED
RIGHTMOST_BUTTON_PRESSED
:COMMON_LVB_
Constants for "GetConsoleScreenBufferInfo", "SetConsoleTextAttribute", "ReadConsoleOutput", "WriteConsoleOutput", "ReadConsoleOutputAttribute", "WriteConsoleOutputAttribute" and "FillConsoleOutputAttribute".
COMMON_LVB_LEADING_BYTE
COMMON_LVB_TRAILING_BYTE
COMMON_LVB_GRID_HORIZONTAL
COMMON_LVB_GRID_LVERTICAL
COMMON_LVB_GRID_RVERTICAL
COMMON_LVB_REVERSE_VIDEO
COMMON_LVB_UNDERSCORE
:CONTROL_KEY_STATE_
Constants for "PeekConsoleInput", "ReadConsoleInput" and "WriteConsoleInput".
CAPSLOCK_ON
ENHANCED_KEY
LEFT_ALT_PRESSED
LEFT_CTRL_PRESSED
NUMLOCK_ON
RIGHT_ALT_PRESSED
RIGHT_CTRL_PRESSED
SCROLLLOCK_ON
SHIFT_PRESSED
:CTRL_EVENT_
Constants for "GenerateConsoleCtrlEvent" and "SetConsoleCtrlHandler".
CTRL_BREAK_EVENT
CTRL_C_EVENT
:DISPLAY_MODE_
Constants for "GetConsoleDisplayMode" and "SetConsoleDisplayMode".
CONSOLE_FULLSCREEN
CONSOLE_FULLSCREEN_HARDWARE
CONSOLE_FULLSCREEN_MODE
CONSOLE_WINDOWED_MODE
:EVENT_TYPE_
Constants for "PeekConsoleInput", "ReadConsoleInput" and "WriteConsoleInput".
KEY_EVENT
MOUSE_EVENT
WINDOW_BUFFER_SIZE_EVENT
MENU_EVENT
FOCUS_EVENT
:FILE_SHARE_
Constants for "CreateConsoleScreenBuffer".
FILE_SHARE_READ
FILE_SHARE_WRITE
:FOREGROUND_
Constants for "GetConsoleScreenBufferInfo", "SetConsoleTextAttribute", "ReadConsoleOutput", "WriteConsoleOutput", "ReadConsoleOutputAttribute", "WriteConsoleOutputAttribute" and "FillConsoleOutputAttribute".
FOREGROUND_BLUE
FOREGROUND_GREEN
FOREGROUND_RED
FOREGROUND_INTENSITY
:GENERIC_
Constants for "CreateConsoleScreenBuffer".
GENERIC_READ
GENERIC_WRITE
:INPUT_MODE_
Constants for "GetConsoleMode" and "SetConsoleMode".
ENABLE_INSERT_MODE
ENABLE_PROCESSED_INPUT
ENABLE_LINE_INPUT
ENABLE_ECHO_INPUT
ENABLE_WINDOW_INPUT
ENABLE_MOUSE_INPUT
ENABLE_QUICK_EDIT_MODE
ENABLE_EXTENDED_FLAGS
ENABLE_VIRTUAL_TERMINAL_INPUT
:MOUSE_
Constants for "PeekConsoleInput", "ReadConsoleInput" and "WriteConsoleInput".
MOUSE_MOVED
DOUBLE_CLICK
MOUSE_WHEELED
MOUSE_HWHEELED
:OUTPUT_MODE_
Constants for "GetConsoleMode" and "SetConsoleMode".
ENABLE_PROCESSED_OUTPUT
ENABLE_WRAP_AT_EOL_OUTPUT
ENABLE_VIRTUAL_TERMINAL_PROCESSING
DISABLE_NEWLINE_AUTO_RETURN
ENABLE_LVB_GRID_WORLDWIDE
:STD_HANDLE_
Constants for "GetStdHandle" and "SetStdHandle"
STD_ERROR_HANDLE
STD_INPUT_HANDLE
STD_OUTPUT_HANDLE
:all
All of the above.
CAVEATS
Not all functions listed here are supported on every version of Windows. Where possible, the platform support is detected, and if there are limitations, a Windows error code ($^E) is set accordingly. In some cases, a workaround is available to circumvent these limitations. Please refer to the official MSDN documentation to verify whether a specific function is supported on your Windows version.
Known limitations
On Windows 7 and 8, WideCharToMultiByte with CP_UTF8 sometimes returns incorrect results when the system locale is not UTF-8. This is a platform limitation, not an issue in the Perl code. Typical symptoms include corrupted characters (e.g., double-encoded UTF-8 sequences).
MSDN - WideCharToMultiByte function:
UTF-8 (CP_UTF8) is supported starting with Windows XP, but full support for
UTF-8 as a system locale was added in later versions of Windows 10
MSDN - Unicode in the Windows API:
Prior to Windows 10 version 1903, UTF-8 was not available as a system code
page. Applications using CP_UTF8 may experience inconsistent behavior if the
system locale is not UTF-8.
REQUIRES
AUTHOR
J. Schneider <brickpool@cpan.org>
LICENSE
MIT License - see LICENSE file for full text. However, this library distributes and references code from other open source projects that have their own licenses.