Microsoft Learn

Developer Documentation

Console I/O

This section provides information about the Windows API functions used for console input and output operations. These functions allow applications to interact with the user through the console window, enabling text-based input and output, cursor manipulation, color control, and more.

Key Concepts

  • Console Handles: Console I/O operations are performed using handles to the console input buffer and the console screen buffer.
  • Input Buffers: Capture user keystrokes and other input events.
  • Screen Buffers: Manage the text, colors, and cursor position displayed in the console window.
  • Console Modes: Control various aspects of console behavior, such as echoing input, line input, and cursor visibility.

Core Functions

The following are some of the most commonly used functions for console I/O:

Function Description
CreateConsoleScreenBuffer Creates a new console screen buffer.
GetStdHandle Retrieves a handle to the standard input, standard output, or standard error stream.
ReadConsole Reads input from the console input buffer.
WriteConsole Writes output to the console screen buffer.
SetConsoleCursorPosition Sets the position of the cursor in a specified console screen buffer.
SetConsoleTextAttribute Sets the foreground and background color, and style attributes for characters written to a console screen buffer.
GetConsoleScreenBufferInfo Retrieves information about the specified console screen buffer.
ScrollConsoleScreenBuffer Scrolls the contents of a specified rectangular region of a console screen buffer.

Example: Writing to the Console

Here's a simple example demonstrating how to write text to the console:


#include <windows.h>
#include <iostream>

int main() {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    if (hConsole == INVALID_HANDLE_VALUE) {
        std::cerr << "Failed to get console handle." << std::endl;
        return 1;
    }

    const char* message = "Hello, Windows Console!\n";
    DWORD bytesWritten;

    if (!WriteConsoleA(hConsole, message, strlen(message), &bytesWritten, NULL)) {
        std::cerr << "Failed to write to console." << std::endl;
        return 1;
    }

    // Set cursor to a specific position and change color
    COORD pos = { 5, 5 }; // X=5, Y=5
    SetConsoleCursorPosition(hConsole, pos);

    SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY); // Magenta
    const char* coloredMessage = "Colored text!";
    WriteConsoleA(hConsole, coloredMessage, strlen(coloredMessage), &bytesWritten, NULL);
    SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); // Reset to default

    return 0;
}
                
Tip: For advanced console manipulation, explore functions like SetConsoleWindowInfo to resize the console window and Console Control Handlers for managing signals like Ctrl+C.

Related Topics