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

Linux 为打印控制字符实现

Windows 为WINAPI控制台接口实现

功能:

移动到上一行

移动到下一行

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

cpp 复制代码
    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
    }
相关推荐
orion571 天前
Missing Semester Class1:course overview and introduction of shell
linux
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户120487221612 天前
Linux驱动编译与加载
linux·嵌入式
用户805533698032 天前
Input 子系统架构:Core、Handler、Driver 三层是怎么协作的
linux·嵌入式
用户805533698032 天前
RK-Forge外设系列开篇 - 把板子从「能启动」变成「能用」:Ethernet/SPI/MMC 三个纯接线外设
linux·github·嵌入式
七歌杜金房2 天前
我终于又有了自己的 Linux 电脑
linux·debian·mac
郝学胜_神的一滴3 天前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
tntxia3 天前
linux curl命令详解_curl详解
linux
扛枪的书生3 天前
Linux 网络管理器用法速查
linux
见过夏天3 天前
C++ 基础入门完全指南
c++