Xcode Swift Command Line Tool reads 1 char from ke

2019-08-04 12:53发布

问题:

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;
}