Linux get key code

Get the Keyboard keycodes keys in Linux

I need to get the keycodes from keyboard input (but after) in Linux, i been able to find the keycodes in Windows only. Using a enum i can make it cross-platform, heres is a piece (not complete, is too large) of the enum code:

 #ifdef _WIN32 # include inline e_IWEKey getKey(uchar OSKey) < switch (OSKey) < // Digits / Numbers case 0x30: return IWEKeys::D0; case 0x31: return IWEKeys::D1; case 0x32: return IWEKeys::D2; case 0x33: return IWEKeys::D3; case 0x34: return IWEKeys::D4; case 0x35: return IWEKeys::D5; case 0x36: return IWEKeys::D6; case 0x37: return IWEKeys::D7; case 0x38: return IWEKeys::D8; case 0x39: return IWEKeys::D9; // Letters case 0x41: return IWEKeys::A; case 0x42: return IWEKeys::B; case 0x43: return IWEKeys::C; case 0x44: return IWEKeys::D; case 0x45: return IWEKeys::E; case 0x46: return IWEKeys::F; case 0x47: return IWEKeys::G; case 0x48: return IWEKeys::H; case 0x49: return IWEKeys::I; case 0x4A: return IWEKeys::J; case 0x4B: return IWEKeys::K; case 0x4C: return IWEKeys::L; case 0x4D: return IWEKeys::M; case 0x4E: return IWEKeys::N; case 0x4F: return IWEKeys::O; case 0x50: return IWEKeys::P; case 0x51: return IWEKeys::Q; case 0x52: return IWEKeys::R; case 0x53: return IWEKeys::S; case 0x54: return IWEKeys::T; case 0x55: return IWEKeys::U; case 0x56: return IWEKeys::V; case 0x57: return IWEKeys::W; case 0x58: return IWEKeys::X; case 0x59: return IWEKeys::Y; case 0x5A: return IWEKeys::Z; // Function Keys case VK_F1: return IWEKeys::F1; case VK_F2: return IWEKeys::F2; case VK_F3: return IWEKeys::F3; case VK_F4: return IWEKeys::F4; case VK_F5: return IWEKeys::F5; case VK_F6: return IWEKeys::F6; case VK_F7: return IWEKeys::F7; case VK_F8: return IWEKeys::F8; case VK_F9: return IWEKeys::F9; case VK_F10: return IWEKeys::F10; case VK_F11: return IWEKeys::F11; case VK_F12: return IWEKeys::F12; case VK_F13: return IWEKeys::F13; case VK_F14: return IWEKeys::F14; case VK_F15: return IWEKeys::F15; case VK_F16: return IWEKeys::F16; case VK_F17: return IWEKeys::F17; case VK_F18: return IWEKeys::F18; case VK_F19: return IWEKeys::F19; case VK_F20: return IWEKeys::F20; case VK_F21: return IWEKeys::F21; case VK_F22: return IWEKeys::F22; case VK_F23: return IWEKeys::F23; case VK_F24: return IWEKeys::F24; >> #endif 

but i never find the Linux keycodes, i need to use the internal Linux API (or POSIX), the X11 API or toolkit-specific API? (as Qt). Thanks.

Источник

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:

Читайте также:  Hp 2014 драйвер linux

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).

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
Читайте также:  Удалить последние обновления linux

Источник

Keyboard input (Русский)

Состояние перевода: На этой странице представлен перевод статьи Keyboard input. Дата последней синхронизации: 13 февраля 2022. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

Необходимым условием для изменения сопоставления клавиш является понимание того, как нажатие клавиши приводит к появлению символа:

  1. Клавиатура посылает компьютеру скан-код (scancode).
  2. Ядро Linux сопоставляет сканкод с кодом клавиши (keycode); смотрите Map scancodes to keycodes.
  3. Раскладка клавиатуры сопоставляет код клавиши с символом клавиши (keysym) в зависимости от того, какие клавиши-модификаторы нажаты.
    1. Для консоли Linux смотрите статью Конфигурация клавиатуры в консоли.
    2. Для Xorg и Wayland смотрите статью Конфигурация клавиатуры в Xorg.

    Большинство ваших клавиш уже должны иметь код клавиши или хотя бы скан-код. Клавиши без скан-кода не распознаются ядром; это могут быть дополнительные клавиши от «игровых» клавиатур и т.д.

    В Xorg некоторым символам клавиш (например XF86AudioPlay , XF86AudioRaiseVolume ) можно назначить действия (такие как запуск внешних приложений). Подробности смотрите в статье Горячие клавиши#Xorg.

    В консоли Linux некоторым символам клавиш (например, F1 – F246 ) могут быть назначены определённые действия (например, переключение на другую консоль или печать некоторой последовательности символов). Подробности смотрите в статье Конфигурация клавиатуры в консоли#Создание своей раскладки.

    Определение скан-кодов

    С помощью showkey

    Традиционный способ узнать скан код — воспользоваться утилитой showkey(1) . showkey ожидает нажатия клавиши, или выходит, если не было нажатий в течение 10 секунд. Чтобы работать с showkey, вы должны быть в виртуальной консоли, а не в графическом окружении или работать, залогинившись по сети. Выполните следующую команду:

    и понажимайте клавиши на клавиатуре; вы должны увидеть скан коды на экране.

    С помощью evtest

    Для USB клавиатур, видимо, нужно использовать evtest(1) из пакета evtest вместо showkey:[1]

    # evtest /dev/input/event12 . 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 ------------

    Совет: Если вы не знаете, какой event-номер имеет интересующее вас устройство, вы можете запустить evtest без параметров, и он покажет вам список устройств с их event-номерами, после чего вы можете ввести нужный номер.

    Используйте поле «value» из MSC_SCAN . В этом примере показано, что NumLock имеет сканкод 70053 и keycode 69.

    С помощью dmesg

    Примечание: Этот метод не показывает скан коды всех клавиш, он показывает их только для неизвестных клавиш.

    Вы можете узнать скан-код клавиши, нажав её и посмотрев вывод команды dmesg. Например, если у вас отображается такая строка:

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

    значит, скан код нужной вам клавиши — 0xa0 .

    Определение кодов клавиш

    Коды клавиш Linux определены в файле /usr/include/linux/input-event-codes.h (смотрите переменные KEY_ ).

    Определение кодов клавиш в консоли

    В виртуальной консоли Linux коды клавиш можно узнать утилитой showkey(1) . showkey ждёт нажатия клавиш, и если нажатий нет в течение 10 секунд, выходит (это единственный способ выйти из программы) Чтобы работать с showkey, вы должны быть в виртуальной консоли, а не в графическом окружении. Выполните следующую команду:

    и понажимайте клавиши на клавиатуре. Вы должны увидеть коды клавиш на экране.

    Определение кодов клавиш в Xorg

    В графическом режиме коды клавиш, которые использует Xorg, можно узнать с помощью утилиты xev(1) , которая поставляется в пакете xorg-xev . Разумеется, чтобы работать с xev, вы должны находиться в графическом окружении, а не в консоли.

    Выполнив следующую команду, вы запустите xev с выводом только релевантной информации:

    $ xev | awk -F'[ )]+' '/^KeyPress/ < a[NR+2] >NR in a < printf "%-3s %s\n", $5, $8 >'
    38 a 55 v 54 c 50 Shift_L 133 Super_L 135 Menu

    Xbindkeys — ещё одна обёртка для xev, которая сообщает коды клавиш.

    Если вы нажимаете клавишу и ничего не появляется на терминале, это может означать, что либо у клавиши нет скан кода, либо сканкоду не назначен код клавиши, либо какой-то другой процесс отлавливает нажатия клавиш. Если вы подозреваете, что процесс, слушающий X сервер отлавливает нажатия клавиш, вы можете попробовать запустить xev из чистой X сессии:

    Смотрите также

    Источник

    Linux get key code

    NAME

    showkey - examine the codes sent by the keyboard

    SYNOPSIS

    showkey [-h|--help] [-a|--ascii] [-s|--scancodes] [-k|--keycodes]

    DESCRIPTION

    showkey prints to standard output either the scan codes or the keycode or the `ascii' code of each key pressed. In the first two modes the program runs until 10 seconds have elapsed since the last key press or release event, or until it receives a suitable signal, like SIGTERM, from another process. In `ascii' mode the program terminates when the user types ^D. When in scancode dump mode, showkey prints in hexadecimal format each byte received from the keyboard to the standard output. A new line is printed when an interval of about 0.1 seconds occurs between the bytes received, or when the internal receive buffer fills up. This can be used to determine roughly, what byte sequences the keyboard sends at once on a given key press. The scan code dumping mode is primarily intended for debugging the keyboard driver or other low level interfaces. As such it shouldn't be of much interest to the regular end-user. However, some modern keyboards have keys or buttons that produce scancodes to which the kernel does not associate a keycode, and, after finding out what these are, the user can assign keycodes with setkeycodes(8). When in the default keycode dump mode, showkey prints to the standard output the keycode number or each key pressed or released. The kind of the event, press or release, is also reported. Keycodes are numbers assigned by the kernel to each individual physical key. Every key has always only one associated keycode number, whether the keyboard sends single or multiple scan codes when pressing it. Using showkey in this mode, you can find out what numbers to use in your personalized keymap files. When in `ascii' dump mode, showkey prints to the standard output the decimal, octal, and hexadecimal value(s) of the key pressed, according to he present keymap.

    OPTIONS

    -h --help showkey prints to the standard error output its version number, a compile option and a short usage message, then exits. -s --scancodes Starts showkey in scan code dump mode. -k --keycodes Starts showkey in keycode dump mode. This is the default, when no command line options are present. -a --ascii Starts showkey in `ascii' dump mode.

    2.6 KERNELS

    In 2.6 kernels key codes lie in the range 1-255, instead of 1-127. Key codes larger than 127 are returned as three bytes of which the low order 7 bits are: zero, bits 13-7, and bits 6-0 of the key code. The high order bits are: 0/1 for make/break, 1, 1. In 2.6 kernels raw mode, or scancode mode, is not very raw at all. Scan codes are first translated to key codes, and when scancodes are desired, the key codes are translated back. Various transformations are involved, and there is no guarantee at all that the final result corresponds to what the keyboard hardware did send. So, if you want to know the scan codes sent by various keys it is better to boot a 2.4 kernel. Since 2.6.9 there also is the boot option atkbd.softraw=0 that tells the 2.6 kernel to return the actual scan codes.

    SEE ALSO

    loadkeys(1), dumpkeys(1), keymaps(5), setkeycodes(8) 1 Feb 1998 SHOWKEY(1)

    © 2019 Canonical Ltd. Ubuntu and Canonical are registered trademarks of Canonical Ltd.

    Источник

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