Question

Comment détecter un événement de clavier en langage C sans utiliser de bibliothèques tierces? Devrais-je utiliser le traitement du signal?

Était-ce utile?

La solution

Il n'y a pas de méthode standard, mais elles devraient vous aider à démarrer.

Windows:

getch();

Unix:

Utilisez ce code du livre Unix Programming de W. Richard Stevens pour définir votre terminal en mode brut, puis utilisez read ().

static struct termios   save_termios;
static int              term_saved;

int tty_raw(int fd) {       /* RAW! mode */
    struct termios  buf;

    if (tcgetattr(fd, &save_termios) < 0) /* get the original state */
        return -1;

    buf = save_termios;

    buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
                    /* echo off, canonical mode off, extended input
                       processing off, signal chars off */

    buf.c_iflag &= ~(BRKINT | ICRNL | ISTRIP | IXON);
                    /* no SIGINT on BREAK, CR-toNL off, input parity
                       check off, don't strip the 8th bit on input,
                       ouput flow control off */

    buf.c_cflag &= ~(CSIZE | PARENB);
                    /* clear size bits, parity checking off */

    buf.c_cflag |= CS8;
                    /* set 8 bits/char */

    buf.c_oflag &= ~(OPOST);
                    /* output processing off */

    buf.c_cc[VMIN] = 1;  /* 1 byte at a time */
    buf.c_cc[VTIME] = 0; /* no timer on input */

    if (tcsetattr(fd, TCSAFLUSH, &buf) < 0)
        return -1;

    term_saved = 1;

    return 0;
}


int tty_reset(int fd) { /* set it to normal! */
    if (term_saved)
        if (tcsetattr(fd, TCSAFLUSH, &save_termios) < 0)
            return -1;

    return 0;
}

Autres conseils

Qu'en est-il du bon vieux kbhit ? Si je comprends bien la question, cela fonctionnera. Voici l'implémentation de kbhit sous Linux.

Malheureusement, la norme C n’a aucune possibilité de détecter les événements de clavier. Vous devez compter sur des extensions spécifiques à la plate-forme. La gestion du signal ne vous aidera pas.

Vous devriez vraiment utiliser des bibliothèques tierces. Il n’existe aucun moyen de le faire indépendamment de la plate-forme dans ANSI C. Le traitement du signal n’est pas la solution.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top