How to force release of a keyboard modifiers

If you have xdotool installed, you could just simply use

xdotool keyup ISO_Level3_Shift

Which sends a key release (for ISO_Level3_Shift, of course) event to the X server.

But you wanted a program to release all modifier keys. One could use xdotool to achieve that easily, if not for that I have no idea what modifier keysyms are defined. One possible method of finding them is to parse keysymdef.h:

grep '^#define' /usr/include/X11/keysymdef.h | sed -r 's/^#define XK_(\S*?).*$/\1/;' | grep -E '_(L|R|Level.*)$'

Which returns some keysyms that surely are modifiers. Unfortunately, I can't find any precise definition of a modifier key right now, so I don't know whether that's a complete list.

Appending | xargs xdotool keyup to the above pipeline will release all those keys. On my system, it executes the following command:

xdotool keyup Shift_L Shift_R Control_L Control_R Meta_L Meta_R Alt_L Alt_R Super_L Super_R Hyper_L Hyper_R ISO_Level2_Latch ISO_Level3_Shift ISO_Level3_Latch ISO_Level3_Lock ISO_Level5_Shift ISO_Level5_Latch ISO_Level5_Lock

I discovered that for my system, the posted solution involving xdotool often didn't cover the key that was stuck, and running setxkbmap didn't seem to accomplish anything on my system.

The solution that I discovered, which has so far worked without fail, is to use x11vnc. Specifically, I use the following the command:

x11vnc -deny_all -clear_keys -timeout 1

-clear_keys is the key part, here. It instructs x11vnc to clear all pressed keys when it exits. -timeout 1 tells x11vnc to quit after 1 second without connections, and -deny_all makes sure no one can connect during that window.

Sometimes the key that gets stuck prevents any meaningful interaction with the desktop, in which case I'll execute the following through ssh:

env DISPLAY=:0 XAUTHORITY=/home/[username]/.Xauthority x11vnc -deny_all -clear_keys -timeout 1

I use "setxkbmap" with no arguments. It seems to reset the keyboard. I have a "shortcut" in my panel that I can use with a mouse for when the keyboard is completely inoperable.