C/C++ 控制台窗口光标移动位置实现(Linux/Windows)

2023-12-20 16:29:57

Linux 为打印控制字符实现

Windows 为WINAPI控制台接口实现

功能:

移动到上一行

移动到下一行

定位控制台光标位置到指定X,Y坐标

    static bool MoveConsoleCursorPositionToPreviousNextLine(bool previous, int line) noexcept {
        if (line < 0) {
            return false;
        }

        if (line == 0) {
            return true;
        }

#ifdef _WIN32
        CONSOLE_SCREEN_BUFFER_INFO csbi;
        HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
        if (NULL == hConsole) {
            return false;
        }

        if (!GetConsoleScreenBufferInfo(hConsole, &csbi)) {
            return false;
        }

        COORD pos{};
        pos.X = csbi.dwCursorPosition.X;
        pos.Y = previous ? csbi.dwCursorPosition.Y - 1 : csbi.dwCursorPosition.Y + 1;

        return SetConsoleCursorPosition(hConsole, pos);
#else
        return ::fprintf(stdout, previous ? "\033[%dA" : "\033[%dB", line) > 0;
#endif
    }

    bool MoveConsoleCursorPositionToPreviousLine(int line) noexcept {
        return MoveConsoleCursorPositionToPreviousNextLine(true, line);
    }

    bool MoveConsoleCursorPositionToNextLine(int line) noexcept {
        return MoveConsoleCursorPositionToPreviousNextLine(false, line);
    }

    bool SetConsoleCursorPosition(int x, int y) noexcept {
#ifdef _WIN32
        HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
        if (NULL == hConsole) {
            return false;
        }

        COORD coord = { (SHORT)x, (SHORT)y };
        return ::SetConsoleCursorPosition(hConsole, coord);
#else
        return ::fprintf(stdout, "\033[%d;%dH", x, y) > 0;
#endif
    }

文章来源:https://blog.csdn.net/liulilittle/article/details/135062597
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。