配置按键重复延迟以检测是否按下按键 [英] Configure key repeat delay to detect if key is being pressed

查看:82
本文介绍了配置按键重复延迟以检测是否按下按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C编写一个程序,该程序使用ncurses来检查是否按下了某个键。问题是键重复存在延迟。

I am writing a program in C that uses ncurses to check if a key is being pressed. The problem is that there is a key repeat delay.

例如,如果我在终端中按住键 a,则在获得 a之前会有短暂的延迟反复输入。我想能够从实际按下的位置知道它是否在被按下。

If I for example hold the key 'a' while in the terminal there is a short delay before 'a' gets repeatedly entered. I want to be able to know if it is being pressed from the point where it is actually pressed.

如何在操作过程中暂时将此延迟更改为等于0。终奌站?我当前正在使用Mac OSX 10.10.5。

How do temporarily change this delay to be equal to 0 while in the terminal? I'm currently using Mac OSX 10.10.5.

推荐答案

尝试使用此方法来忽略缓冲的按键重复:

Try this to ignore buffered key repeats:

int key;
if ((key = getch()) != ERR) {
  while (getch() == key);
}

在上下文中:

//example.c

#include <ncurses.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
  int pos_x = 0;
  int max_x = 0, max_y = 0;
  int key = 0;
  int on = 1;

  initscr();
  noecho();
  cbreak();
  curs_set(FALSE);
  keypad(stdscr, TRUE);
  nodelay(stdscr, TRUE);
  getmaxyx(stdscr,max_y,max_x);

  while(1) {
    clear();
    mvprintw(0, 0, "Press, hold and release L-R arrow keys. Press UP/DOWN to toggle function.");
    mvprintw(1, 0, "Skip buffered repeats: %s", (on ? "ON" : "OFF"));
    mvprintw(2, pos_x, "@");
    refresh();
    usleep(50000);
    getmaxyx(stdscr,max_y,max_x);
    key = getch();

    // skip buffered repeats                                                                                     
    if (on) {
      if (key != ERR) {
        while (getch() == key);
      }
    }
    //                                                                                                           

    switch (key) {
    case KEY_LEFT:
      pos_x += (pos_x > 0 ? -1 : 0); break;
    case KEY_RIGHT:
      pos_x += (pos_x < max_x - 1 ? 1 : 0); break;
    case KEY_UP:
      on = 1; break;
    case KEY_DOWN:
      on = 0; break;
    }
  }
  endwin();
}

编译并使用 gcc example.c -lncurses -oexample&& ./example

这篇关于配置按键重复延迟以检测是否按下按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆