Xcode Swift Command Line Tool reads 1 char from keyboard without echo or need to press return [closed]

爱⌒轻易说出口 提交于 2019-12-11 11:03:38

问题


I need a function, like the old "getch()", in Objective C or Swift to read one single character from the keyboard without echo and without the nedd to press return after the character has been typed to make the function continue.

This is, I know, only interesting when programming command line tools, perhaps to make a selection or write an editor.


回答1:


Here is the function for use with Swift, written in Swift:

func GetKeyPress () -> Int
{
    var key: Int = 0
    var c: cc_t = 0
    var cct = (c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c) // Set of 20 Special Characters
    var oldt: termios = termios(c_iflag: 0, c_oflag: 0, c_cflag: 0, c_lflag: 0, c_cc: cct, c_ispeed: 0, c_ospeed: 0)

    tcgetattr(STDIN_FILENO, &oldt) // 1473
    var newt = oldt
    newt.c_lflag = 1217  // Reset ICANON and Echo off
    tcsetattr( STDIN_FILENO, TCSANOW, &newt)
    key = Int(getchar())  // works like "getch()"
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt)
    return key
}



回答2:


Here is the function for use with Objective-C and Swift, written in C:

#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <string.h>

int Get_Key (void) {
    int key;
    struct termios oldt, newt;
    tcgetattr( STDIN_FILENO, &oldt); // 1473
    memcpy((void *)&newt, (void *)&oldt, sizeof(struct termios));
    newt.c_lflag &= ~(ICANON);  // Reset ICANON
    newt.c_lflag &= ~(ECHO);    // Echo off, after these two .c_lflag = 1217
    tcsetattr( STDIN_FILENO, TCSANOW, &newt); // 1217
    key=getchar(); // works like "getch()"
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
    return key;
}


来源:https://stackoverflow.com/questions/25551321/xcode-swift-command-line-tool-reads-1-char-from-keyboard-without-echo-or-need-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!