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

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
    }

你可能感兴趣的:(C/C++,c语言,c++,linux)