I'd like to be able to execute a command when switching to specific applications. In particular, I'd like to able to change the xmodmap when switching to the Terminal and then change it again when switching away (e.g. to firefox).

I figure that it may be possible to detect when an application comes to the foreground, and then run xmodmap?

How would I do this (esp. on Ubuntu 19.04, X11)?

Some things I've discovered:

There is a visibilityNotify event which the X server can produce. Not sure how to utilise this and whether it does what I want?

"xdotool search --class Terminal behave %@ focus getwindowpid" notifies on focus change, which is great. However, getactivewindow causes a segmentation fault, so I cannot actually get the window id for use with xwininfo or similar. Any ideas along those lines?

1 Answer 1


The following perl script tracks the window that has 'input focus'.

open F,"xdotool search --class '.' behave %@ focus getwindowpid |";
while (<F>) {
    ($f = `xdotool getwindowfocus`) =~s/\n//;
    my $hex = sprintf("0x%X", $f);
    $hex = lc($hex);
    $hex =~ s/0x//;
    print `wmctrl -lGpx | grep '$hex'`;

Note that xdotool also sends events when a window loses focus, so the output is not as clean as one would want it. However, with this it's possible to tell whether a new window has acquired focus.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.