Use keys for mouse buttons on linux. Alternative to AHK?

On windows I have an autohotkey script which:

  • Only works when caps lock is on
  • Generates left, middle and right mouse button events when left control, menu and alt keys are pressed
  • Allows holding the keys down (for dragging objects)

Is there an easy way of duplicating this functionality in linux?


Keymapping - mouse click - middle click How to Map Mouse buttons to Keyboard keys

Firstly, disable keypad controlling mouse so xev can capture the keycode Then type the command:

$ xev

Then move your mouse into the little new window that pops up. Press a mouse button to find out the name of that button: See below, I found one of my mouse buttons is called "button 1"

ButtonPress event, serial 37, synthetic NO, window 0x6200001,
    root 0x29d, subw 0x6200002, time 2427401, (31,41), root:(652,407),
    state 0x0, button 1, same_screen YES

Then find out which keyboard key you want to map that mouse button to: Press a keyboard key and find the keycode.

When pressing the space key on my keyboard, the terminal shows:

KeyPress event, serial 37, synthetic NO, window 0x6200001,
    root 0x29d, subw 0x0, time 2152399, (398,60), root:(1019,426),
    state 0x0, keycode 65 (keysym 0x20, space), same_screen YES,
    XLookupString gives 1 bytes: (20) " "
    XmbLookupString gives 1 bytes: (20) " "
    XFilterEvent returns: False

from above, we have found that the keycode for the Space key is 65 So you need to find the keycodes of the keys you want to map mouse buttons to...

Then the next step:

$ sudo apt-get install xkbset

Then copy the script below and save it into a file called keymap_mouse2kb.sh

of course change the keyboard keycodes to the ones you want

#!/bin/bash
# set XKB layout
setxkbmap -layout us
# turn on mousekeys
xkbset m
# stop mousekeys expiring after a timeout
xkbset exp =m
# map keysym to other keysym
#xmodmap -e "keysym Menu = Pointer_Button2"
# this also works
 xmodmap -e "keycode 66 = Pointer_Button2"
 xmodmap -e "keycode 133 = Pointer_Button1"
 xmodmap -e "keycode 88 = Pointer_Button3"

Then make this file executable by

$ sudo chmod u+x keymap_mouse2kb.sh

Then run it when you need it... e.g. at booting up

$ ./keymap_mouse2kb.sh

X has a built-in mechanism for controlling the mouse cursor with the keyboard. Press the Pointer_EnableKeys key to activate this mode (mouse keys mode); it's usually bound to Shift+NumLock.

In mouse keys mode, the keypad arrows move the pointer around, and the other keypad keys emulate buttons (/*- are left, middle, right respectively; + is left double-click, and 0 and . are left press and release).

See mouse keys for more information. By the way, this mode can be enabled on Windows too.


I had a similar need. I couldn't find any existing solution that met all my needs, so I wrote a little utility to do it and put it on GitHub.

https://github.com/SalmonChris/KeyboardMouse