C++拾趣——绘制Console中PushButton

《C++拾趣——绘制Console中单个进度条》中,我们熟悉了怎么制作一个进度条。现在我们开始制作更复杂的控件。本节我们就做一个PushButton控件。
在这里插入图片描述

居中显示窗口

按照界面库的设计,Button不能独立存在,而是要位于一个窗口中。我们就用线段画出一个窗口。

这个窗口要位于终端中间,即居中。这样我们就需要先获取终端窗口的尺寸。

    // 获取终端窗口大小
    struct winsize w;
    ioctl(STDIN_FILENO, TIOCGWINSZ, &w);
    int terminalWidth = w.ws_col;
    int terminalHeight = w.ws_row;

然后通过当前窗口的大小,计算出起始绘制的坐标

    // 窗口的宽度和高度
    int windowWidth = 40;
    int windowHeight = 8;

    // 计算窗口的起始位置
    int startX = (terminalWidth - windowWidth) / 2;
    int startY = (terminalHeight - windowHeight) / 2;

清屏并重设光标

在开始绘制之前,我们需要使用《C++拾趣——绘制Console中圆形进度》中介绍的\033[2J\033[H来清屏并将光标移动到左上角。这是我们需要反复从最开始的位置重新绘制所有内容。

    cout << "\033[2J\033[H"; // 清屏并将光标移动到左上角

绘制窗口

绘制窗口顶部

在这里插入图片描述
因为要居中,所以在Y轴方向,我们先要输出一些\n来换行。

    // 打印顶部边框
    cout << string(startY, '\n');
    cout << string(startX, ' ') << "+" << string(windowWidth - 2, '-') << "+" << endl;

绘制非按钮行

在这里插入图片描述

    // 打印空行
    for (int i = 0; i < windowHeight - 4; ++i) {
        cout << string(startX, ' ') << "| " << string(windowWidth - 4, ' ') << " |" << endl;
    }

绘制按钮行

在这里插入图片描述
我们需要绘制两个按钮:OK和Cancel。由于按钮行比较特殊,绘制的复杂度也会高些。

因为按钮也要居中显示,所以我们先需要算出要空出多少列出来——padding值。

当按钮被选中时,它会变成绿色背景,另外一个按钮就会变成默认背景。

    // 打印按钮行
    string okButton = "[ OK ]";
    string cancelButton = "[Cancel]";
    int totalButtonLength = okButton.length() + cancelButton.length() + 2; // 2 spaces between buttons
    int padding = (windowWidth - totalButtonLength) / 2;

    cout << string(startX, ' ') << "| " << string(padding, ' ');
    if (isButtonSelected && buttonIndex == 0) {
        cout << greenBackground << whiteText << blinkText << okButton << reset;
    } else {
        cout << okButton;
    }
    cout << "  ";
    if (isButtonSelected && buttonIndex == 1) {
        cout << greenBackground << whiteText << blinkText << cancelButton << reset;
    } else {
        cout << cancelButton;
    }
    cout << string(windowWidth - totalButtonLength - padding - 4, ' ') << " |" << endl;

绘制窗口底部

在这里插入图片描述

    // 打印底部边框
    cout << string(startX, ' ') << "+" << string(windowWidth - 2, '-') << "+" << endl;

修改终端默认行为

由于不能鼠标操作,所以我们只能通过键盘操作界面,比如进行Button的选择和按下操作。

我们只接受Tab,->,<-、ESC和Enter等5个键。Tab、->和<-键只能进行Button的切换;ESC是退出程序;Enter表示Button被按下。

默认情况下,我们在键盘上输出的可见字符都会显示在终端上。但是在当前场景下,我们并不希望有这样的效果。这就需要我们修改终端的默认行为。

下面的代码在将终端修改为静默模式(关闭规范模式(ICANON)和回显(ECHO),使得输入字符不需要按下回车键就能立即读取,并且输入的字符不会显示在终端上)后,等待并读取键盘的输入,然后再还原原始的设置。这步还原操作非常重要,否则程序退出后,终端会一直处于静默模式,后续的输入都不会显示在终端上。这也预示着,如果本程序使用ctrl+c强行终止,会出现终端行为异常的情况。

int getch() {
    struct termios oldt, newt;
    int ch;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);   // 修改终端设置:关闭回显和规范模式
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);    // 设置终端为静默模式
    ch = getchar();
    ……
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return ch;
}

对方向键的特殊处理

在终端环境中,特殊键(如箭头键、功能键等)通常不会直接生成单个字符的输入,而是生成一系列字符的序列。对于箭头键,通常的序列是以 ESC 键(ASCII 码 27)开头,后面跟着一个或多个字符来表示具体的键。

  • 向上箭头:ESC + [ + A
  • 向下箭头:ESC + [ + B
  • 向右箭头:ESC + [ + C
  • 向左箭头:ESC + [ + D

由于我们只接受向左和向右的方向键,所以需要将它们对应的组合转换成其他整型数。

    ch = getchar();
    if (ch == 27) { // 如果是ESC键
        ch = getchar();
        if (ch == 91) { // 如果是'['键
            ch = getchar();
            if (ch == 67) ch = 1000; // 向右箭头键
            if (ch == 68) ch = 1001; // 向左箭头键
        }
    }

过程控制

下面代码会在getch()中等待终端的输入。

如果输入的是Tab、向下键或者向上键,都会切换Button的聚焦——由buttonIndex 表示。

如果输入的是Enter键,就会退出程序,并输出用户的选择。

如果遇到ESC,则直接退出程序。

int main() {
    bool isButtonSelected = true;
    int buttonIndex = 0;

    while (true) {
        display(isButtonSelected, buttonIndex);

        int ch = getch();
        if (ch == 9 || ch == 1001 || ch == 1000) { // Tab 键或下箭头键或上箭头键
            buttonIndex = (buttonIndex + 1) % 2;
        } else if (ch == 10 || ch == 13) { // Enter 键
            if (buttonIndex == 0) { // OK 按钮
                cout << "You selected: OK" << endl;
            } else if (buttonIndex == 1) { // Cancel 按钮
                cout << "You selected: Cancel" << endl;
            }
            break;
        } else if (ch == 27) { // Esc 键退出
            break;
        }
    }

    return 0;
}

完整代码

#include <iostream>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>

using namespace std;

void display(bool isButtonSelected, int buttonIndex) {
    const string greenBackground = "\033[42m"; // 绿色背景
    const string whiteText = "\033[37m";       // 白色字体
    const string blinkText = "\033[5m";        // 闪烁文本
    const string reset = "\033[0m";            // 重置颜色

    // 获取终端窗口大小
    struct winsize w;
    ioctl(STDIN_FILENO, TIOCGWINSZ, &w);
    int terminalWidth = w.ws_col;
    int terminalHeight = w.ws_row;

    // 窗口的宽度和高度
    int windowWidth = 40;
    int windowHeight = 8;

    // 计算窗口的起始位置
    int startX = (terminalWidth - windowWidth) / 2;
    int startY = (terminalHeight - windowHeight) / 2;

    cout << "\033[2J\033[H"; // 清屏并将光标移动到左上角

    // 打印顶部边框
    cout << string(startY, '\n');
    cout << string(startX, ' ') << "+" << string(windowWidth - 2, '-') << "+" << endl;

    // 打印空行
    for (int i = 0; i < windowHeight - 4; ++i) {
        cout << string(startX, ' ') << "| " << string(windowWidth - 4, ' ') << " |" << endl;
    }

    // 打印按钮行
    string okButton = "[ OK ]";
    string cancelButton = "[Cancel]";
    int totalButtonLength = okButton.length() + cancelButton.length() + 2; // 2 spaces between buttons
    int padding = (windowWidth - totalButtonLength) / 2;

    cout << string(startX, ' ') << "| " << string(padding, ' ');
    if (isButtonSelected && buttonIndex == 0) {
        cout << greenBackground << whiteText << blinkText << okButton << reset;
    } else {
        cout << okButton;
    }
    cout << "  ";
    if (isButtonSelected && buttonIndex == 1) {
        cout << greenBackground << whiteText << blinkText << cancelButton << reset;
    } else {
        cout << cancelButton;
    }
    cout << string(windowWidth - totalButtonLength - padding - 4, ' ') << " |" << endl;

    // 打印底部边框
    cout << string(startX, ' ') << "+" << string(windowWidth - 2, '-') << "+" << endl;

    cout << reset; // 重置颜色
}

int getch() {
    struct termios oldt, newt;
    int ch;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);   // 修改终端设置:关闭回显和规范模式
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);    // 设置终端为静默模式
    ch = getchar();
    if (ch == 27) { // 如果是ESC键
        ch = getchar();
        if (ch == 91) { // 如果是'['键
            ch = getchar();
            if (ch == 67) ch = 1000; // 向右箭头键
            if (ch == 68) ch = 1001; // 向左箭头键
        }
    }
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return ch;
}

int main() {
    bool isButtonSelected = true;
    int buttonIndex = 0;

    while (true) {
        display(isButtonSelected, buttonIndex);

        int ch = getch();
        if (ch == 9 || ch == 1001 || ch == 1000) { // Tab 键或下箭头键或上箭头键
            buttonIndex = (buttonIndex + 1) % 2;
        } else if (ch == 10 || ch == 13) { // Enter 键
            if (buttonIndex == 0) { // OK 按钮
                cout << "You selected: OK" << endl;
            } else if (buttonIndex == 1) { // Cancel 按钮
                cout << "You selected: Cancel" << endl;
            }
            break;
        } else if (ch == 27) { // Esc 键退出
            break;
        }
    }

    return 0;
}

代码地址

https://github.com/f304646673/cpulsplus/tree/master/console_ui/button

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

breaksoftware

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值