以下是使用 C++ 实现控制台上下选择栏的示例代码,其中使用了 Windows API 来控制控制台的显示效果。请注意,该代码仅在 Windows 环境下可用,且可能与其他编译器不兼容。

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

void gotoxy(int x, int y) {
    COORD coord;
    coord.X = x;
    coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void setConsoleColor(int color) {
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}

void drawMenu(int selectedOption) {
    system('cls');  // 清空屏幕

    // 获取控制台尺寸
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
    int consoleWidth = csbi.srWindow.Right - csbi.srWindow.Left + 1;
    int consoleHeight = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;

    // 计算选项的位置
    int option1X = (consoleWidth - 1) / 2;
    int option1Y = (consoleHeight - 2) / 2 - 1;
    int option2X = (consoleWidth - 1) / 2;
    int option2Y = (consoleHeight - 2) / 2 + 1;

    // 绘制选项
    gotoxy(option1X, option1Y);
    if (selectedOption == 1) {
        setConsoleColor(15);  // 设置背景为白色
    }
    std::cout << '1';
    setConsoleColor(7);  // 恢复默认颜色

    gotoxy(option2X, option2Y);
    if (selectedOption == 2) {
        setConsoleColor(15);  // 设置背景为白色
    }
    std::cout << '2';
    setConsoleColor(7);  // 恢复默认颜色
}

int main() {
    int selectedOption = 1;
    drawMenu(selectedOption);

    while (true) {
        // 检测键盘输入
        if (GetAsyncKeyState(VK_UP) & 0x8000) {
            selectedOption = 1;
        } else if (GetAsyncKeyState(VK_DOWN) & 0x8000) {
            selectedOption = 2;
        } else if (GetAsyncKeyState(VK_RETURN) & 0x8000) {
            break;
        }

        drawMenu(selectedOption);
        Sleep(100);  // 等待一段时间,避免检测到连续按键
    }

    // 处理选择结果
    if (selectedOption == 1) {
        std::cout << 'You selected option 1.' << std::endl;
    } else if (selectedOption == 2) {
        std::cout << 'You selected option 2.' << std::endl;
    }

    return 0;
}

这段代码使用了gotoxy()函数来移动控制台光标到指定位置,并使用setConsoleColor()函数来设置控制台文本颜色。drawMenu()函数用于绘制菜单,根据selectedOption参数来确定当前选项,将选中的选项背景设置为白色。通过循环不断检测键盘输入,根据上下箭头键的按下情况来改变selectedOption的值,按下回车键后退出循环。最后根据选择的选项进行相应的处理。

请注意,这段代码使用了 Windows API,并且在 Dev-C++ 5.11 中可能需要手动链接 Windows 库。可能需要在项目设置中添加-luser32选项来链接 User32 库。

C++ 控制台上下选择栏实现:Dev-C++ 5.11 示例

原文地址: https://www.cveoy.top/t/topic/bIQb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录