Linux which key is pressed

How to check if a key was pressed in Linux? [closed]

I’m assuming that you want this on a terminal emulator (and not on an X client), and that you don’t care about key release.

The Linux way to do this would be to use termios(3) to set the terminal to non-canonical or to raw mode, then read stdin using the usual libc functions.

System call numbers on Linux are on /usr/include/asm/unistd.h (or unistd_64.h), but the termios functions end up getting converted to ioctl()’s. So, if you can’t call libc for some strange and unusual reason, you’ll have to lookup the syscall number for ioctl, and the ioctl’s corresponding to termios functions.

Apparently, you’re assuming that Linux uses the same model as DOS, in which the console input is an abstraction of a keyboard (with functions like KEYPRESSED, GETC, . ) and the console output is an abstraction of a character-oriented display.

Unix/Linux abstraction is about terminals, which can be the physical console, a terminal (or terminal emulator) on a serial port, an xterm, . An important point here is that by default, input lines are not made available to programs until the terminal (or terminal emulator) sees a line delimiter.

On POSIX, these terminals are controlled by the termios(3) functions. Linux ends up translating those to ioctl() calls, as follows (see tty_ioctl(4) ):

  • tcgetattr(fd, arg) => ioctl(fd, TCGETS, arg)
  • tcsetattr(fd, TCSANOW, arg) => ioctl(fd, TCSETS, arg)
  • tcsetattr(fd, TCSADRAIN, arg) => ioctl(fd, TCSETSW, arg)
  • tcsetattr(fd, TCSAFLUSH, arg) => ioctl(fd, TCSETSF, arg)
  • .

So, a C program to do what you asked for, using termios(3) and poll(2) (error checking stripped for brevity and clarity):

#include #include #include #include #include #include #include #include static sig_atomic_t end = 0; static void sighandler(int signo) < end = 1; >int main() < struct termios oldtio, curtio; struct sigaction sa; /* Save stdin terminal attributes */ tcgetattr(0, &oldtio); /* Make sure we exit cleanly */ memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = sighandler; sigaction(SIGINT, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); /* This is needed to be able to tcsetattr() after a hangup (Ctrl-C) * see tcsetattr() on POSIX */ memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = SIG_IGN; sigaction(SIGTTOU, &sa, NULL); /* Set non-canonical no-echo for stdin */ tcgetattr(0, &curtio); curtio.c_lflag &= ~(ICANON | ECHO); tcsetattr(0, TCSANOW, &curtio); /* main loop */ while (!end) < struct pollfd pfds[1]; int ret; char c; /* See if there is data available */ pfds[0].fd = 0; pfds[0].events = POLLIN; ret = poll(pfds, 1, 0); /* Consume data */ if (ret >0) < printf("Data available\n"); read(0, &c, 1); >> /* restore terminal attributes */ tcsetattr(0, TCSANOW, &oldtio); return 0; > 

Now, ioctl and poll are syscalls, and you can find their numbers on /usr/include/asm/unistd.h (54 and 168 on x86), and /usr/include/asm/ioctls.h has the ioctl constants you need (on x86: TCGETS=0x5401, TCSETS=0x5402, TCSETSW=0x5403, TCSETSF=0x5404).

Читайте также:  Multiple desktop on linux

Источник

Keyboard input

Prerequisite for modifying the key mapping is knowing how a key press results in a symbol:

  1. The keyboard sends a scancode to the computer.
  2. The Linux kernel maps the scancode to a keycode, see Map scancodes to keycodes.
  3. The keyboard layout maps the keycode to a symbol or keysym, depending on what modifier keys are pressed.
    • For the Linux console, see Linux console/Keyboard configuration.
    • For Xorg and Wayland, see Xorg/Keyboard configuration.

Most of your keys should already have a keycode, or at least a scancode. Keys without a scancode are not recognized by the kernel; these can include additional keys from «gaming» keyboards, etc.

In Xorg, some keysyms (e.g. XF86AudioPlay , XF86AudioRaiseVolume etc.) can be mapped to actions (i.e. launching an external application). See Keyboard shortcuts#Xorg for details.

In Linux console, some keysyms (e.g. F1 to F246 ) can be mapped to certain actions (e.g. switch to other console or print some sequence of characters). See Console keyboard configuration#Creating a custom keymap for details.

Identifying scancodes

Using showkey

The traditional way to get a scancode is to use the showkey(1) utility. showkey waits for a key to be pressed, or exits if no keys are pressed within 10 seconds. For showkey to work you need to be in a virtual console, not in a graphical environment or logged in via a network connection. Run the following command:

and try to push keyboard keys; you should see scancodes being printed to the output.

Using evtest

For USB keyboards, it is apparently necessary to use evtest(1) from the evtest package instead of showkey [1]:

. Event: time 1434666536.001123, type 4 (EV_MSC), code 4 (MSC_SCAN), value 70053 Event: time 1434666536.001123, type 1 (EV_KEY), code 69 (KEY_NUMLOCK), value 0 Event: time 1434666536.001123, -------------- EV_SYN ------------

Tip: If you do not know which event number has device of your interest, you can run evtest without parameters and it will show you list of devices with their event numbers, then you can enter needed number.

Use the «value» field of MSC_SCAN . This example shows that NumLock has scancode 70053 and keycode 69.

Using dmesg

You can get the scancode of a key by pressing the desired key and looking at the output of dmesg. For example, if you get:

Unknown key pressed (translated set 2, code 0xa0 on isa0060/serio0

then the scancode you need is 0xa0 .

Identifying keycodes

The Linux keycodes are defined in /usr/include/linux/input-event-codes.h (see the KEY_ variables).

Читайте также:  Linux command line keys

Identifying keycodes in console

The keycodes for virtual console are reported by the showkey(1) utility. showkey waits for a key to be pressed and if none are, in a span of 10 seconds, it quits. To execute showkey, you need to be in a virtual console, not in a graphical environment. Run the following command:

and try to push keyboard keys; you should see keycodes being printed to the output.

Identifying keycodes in Xorg

This article or section needs expansion.

Reason: xev also reports keysyms. Mention that you need to focus the «Event Tester» window. (Discuss in Talk:Keyboard input)

The keycodes used by Xorg are reported by a utility called xev(1) , which is provided by the xorg-xev package. Of course to execute xev, you need to be in a graphical environment, not in the console.

With the following command you can start xev and show only the relevant parts:

$ xev | awk -F'[ )]+' '/^KeyPress/ < a[NR+2] >NR in a < printf "%-3s %s\n", $5, $8 >'

Here is an example output:

38 a 55 v 54 c 50 Shift_L 133 Super_L 135 Menu

Xbindkeys is another wrapper to xev that reports keycodes.

If you press a key and nothing appears in the terminal, it means that either the key does not have a scancode, the scancode is not mapped to a keycode, or some other process is capturing the keypress. If you suspect that a process listening to X server is capturing the keypress, you can try running xev from a clean X session:

Configuration of VIA compatible keyboards

VIA is a program to remap keys directly into compatible keyboards. In case you have one of those, in order for the keyboard to be picked up by the browser and configure it online, you need to add a custom udev rule changing the permissions of devices accessed through the hidraw driver.

Write this text to /etc/udev/rules.d/99-viia.rules in a text editor:

KERNEL=="hidraw*", SUBSYSTEM=="hidraw", MODE="0666", TAG+="uaccess", TAG+="udev-acl"

In order for this to take effect you need to reload udev with:

See also

  • kbd-project — official website of the showkeys utility
  • wev — wayland event viewer similar to xorg’s xev
  • interception-tools — a set of utilities to control and customize the behavior of keyboard input mappings
  • kmonad — an advanced key rebinding and remapping daemon
  • Hawck — another key rebinding daemon
  • keyd — simplistic key rebinding daemon
  • Vial — VIA standalone program

Источник

How do you check which keys are pressed Linux?

Smart Strategy Games

If you’re at a shell prompt, you can press Ctrl – v and then the key of interest to see what the result is.

How do you check if any key is pressed?

Windows On-Screen Keyboard is a program included with Windows that displays an on-screen keyboard for testing modifier keys and other special keys. For example, when you press the Alt, Ctrl, or Shift key, the on-screen keyboard highlights the keys that were pressed.

How does Ubuntu show which keys are pressed on the screen?

Screenkey is a free and open source alternative to Screenflick designed for use on Linux desktops like Ubuntu. When run, the app will display each keystroke on the screen as you press it (ideally while recording with the GNOME Shell screen recorder or other tool).

Читайте также:  Linux сколько процессоров установлено

How does Python detect the keystroke?

Method 1: Using pynput. In this method, we will use the pynput python module to detect any key presses. “pynput….Focus:

  1. Import Key, Pynput Listener. keyboard.
  2. Create a with statement: The with statement is used to wrap the execution of a block with methods defined by a context manager.
  3. Define functions.

How do I find my key code?

  1. In the vehicle documentation. Sometimes the key code is in the vehicle manual or on a tag with the lock or key.
  2. on the key It would be an engraved or carved code.
  3. On a metal plate in the glove box or elsewhere in the car.
  4. On the lock casing.

How do I get to the keyboard in Linux?

By default, in Ubuntu and Linux Mint, the terminal hotkey is assigned to Ctrl+Alt+T. If you want to change this to something else that makes sense to you, open your menu at System -> Preferences -> Keyboard Shortcuts. Scroll down the window and find the shortcut for “Run a Terminal”.

How do I open the virtual keyboard in Linux?

Open the Activities overview and start typing Settings. Click Settings. Click Accessibility in the sidebar to open the panel. Turn on the screen keyboard in the typing section.

How do I get a Pynput?

To do so, try the following:

  1. open your . py file with Pycharm.
  2. Place your cursor next to the pynput import line.
  3. PyCharm will display the lamp icon next to it (it will definitely be RED)
  4. If it is RED, click on the lamp icon and select the “install pynput package” option.
  5. Once it’s installed, run your script again.

How to check keystroke from keyboard?

The getchar() function will wait for keyboard input, if we don’t press any key it will continue in the same state and the program execution will stop until we press a key.

Where do I find the Mon key in Ubuntu?

On Ubuntu/Debian it is included in the x11-utils package. If you’re looking for something to graphically show you which key is currently pressed (perhaps for the corner of a screencast), key-mon might be the ticket.

What happens when you press the power button on Linux?

That should prevent the system from shutting down, but it means you won’t be able to use the power button to initiate a clean shutdown (waiting non-clean shutdown for 4 seconds, if any, can’t be disabled via systemd like you do system firmware). Thanks for contributing an answer to the Unix & Linux Stack Exchange!

Is there a way to show Alt keys in Linux superuser?

However, when you’re at the console, showkey is what you want. And if you’re in an SSH session or a real terminal, you can use /usr/lib/ncurses/examples/demo_altkeys (available on Debian in the ncurses-examples package).

Источник

Оцените статью
Adblock
detector