OS X - 在 if 语句中按键

OS X - Keypress in an if statement

本文关键字:语句 if OS      更新时间:2023-10-16

我对C++编程和使用Mac作为计算机很陌生。我已经在互联网上搜索了一段时间,但我仍然找不到解决我问题的好方法。

我正在使用键盘箭头制作一个项目,但我不知道如何在 if 语句中制作按键功能。

所以我正在寻找的解决方案是:

if (up arrow is pressed) {
    std::cout << it worked! << std::endl;
}

信息:LLVM编译器,Xcodes命令行工具,Unix,OS X-Sierra。谢谢你的帮助。

好吧,我无法让另一个答案中的代码工作,不确定有什么不同,因为我也在运行 Sierra。但我将其转换为使用tcsetattr。该调用的目的是将终端置于原始模式,以便它直接发送按键。如果您不这样做,则在您按回车键之前,它不会发送任何内容。

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
static struct termios savemodes;
static int havemodes = 0;
int tty_break(void)
{
    struct termios modmodes;
    if (tcgetattr(STDIN_FILENO, &savemodes) < 0)
        return -1;
    havemodes = 1;
    modmodes = savemodes;
    cfmakeraw(&modmodes);
    return tcsetattr(STDIN_FILENO, TCSANOW, &modmodes);
}
int tty_getchar(void)
{
    return getchar();
}
int tty_fix(void)
{
    if(!havemodes)
        return 0;
    return tcsetattr(STDIN_FILENO, TCSANOW, &savemodes);
}
int
main(int argc, char *argv[])
{
    int i;
    if(tty_break() != 0)
        return 1;
    for(i = 0; i < 10; i++)
        printf(" = %dn", tty_getchar());
    tty_fix();
    return 0;
}

我已经将我在注释中链接到的代码放在一个程序中,以便您可以看到它是如何工作的。

#include <stdio.h>
#include <sgtty.h>
static struct sgttyb savemodes;
static int havemodes = 0;
int tty_break()
{
    struct sgttyb modmodes;
    if(ioctl(fileno(stdin), TIOCGETP, &savemodes) < 0)
        return -1;
    havemodes = 1;
    modmodes = savemodes;
    modmodes.sg_flags |= CBREAK;
    return ioctl(fileno(stdin), TIOCSETN, &modmodes);
}
int tty_getchar()
{
    return getchar();
}
int tty_fix()
{
    if(!havemodes)
        return 0;
    return ioctl(fileno(stdin), TIOCSETN, &savemodes);
}
main()
{
    int i;
    if(tty_break() != 0)
        return 1;
    for(i = 0; i < 10; i++)
        printf(" = %dn", tty_getchar());
    tty_fix();
    return 0;
}

您可以简单地编译它:

clang main.c -o main

并运行它:

./main

您将看到 (向上箭头(键导致以下代码:

27 (Escape)
91
65

请注意,代码不是我的 - 它完全是从我上面提到的 C-FAQ 中提取的。