How to move the mouse cursor between monitors with keys in Gnome3?

The script below can be run with two arguments: left and right.

In a two monitor- setup (left/right, in any configuration), the script will move the mouse to the center of either the left- or right monitor, depending on the argument.

enter image description here

The script

#!/usr/bin/env python3
import subprocess
import sys

arg = sys.argv[1]

screeninfo = [
    s for s in subprocess.check_output("xrandr").decode("utf-8").split()\
    if s.count("+") == 2
    ]

if arg == "left":
    match = [s for s in screeninfo if s.endswith("+0+0")][0]
elif arg == "right":
    match = [s for s in screeninfo if not s.endswith("+0+0")][0]

data = [item.split("x") for item in match.split("+")]
numbers = [int(n) for n in [item for sublist in data for item in sublist]]
coord = [str(int(n)) for n in [(numbers[0]/2)+numbers[2], (numbers[1]/2)+numbers[3]]]

subprocess.Popen(["xdotool", "mousemove", coord[0], coord[1]])

How to use

  1. The script needs xdotool:

    sudo apt-get install xdotool
    
  2. Copy the script into an empty file, save it as move_mouse.py

  3. Test-run the script. Run from a terminal the commands:

    python3 /path/to/move_mouse.py left
    

    and

    python3 /path/to/move_mouse.py right
    
  4. If all works fine, add the commands to two available shortcuts: Choose: System Settings > "Keyboard" > "Shortcuts" > "Custom Shortcuts". Click the "+" and add the commands above.

Note

The script is not gnome -specific; it should run fine on all Ubuntu distro's.

Explanation

  • We can move the mouse to specific position by the command (e.g.):

    xdotool mousemove 300 500
    
  • To calculate the targeted positions (centered) in both screens, we need to understand connected screens are positioned in an arbitrary layout, e.g.

    enter image description here

  • In the output of xrandr, we can find information on both screens, their resolutions and their positions in the spanning layout, like:

    1280x1024+1680+128
    
  • To get the targeted position per screen (center), all we need to do is divide the first and second number (1280x1024, the resolution) by 2, subsequently add the two calculated positions to the offset per screen (+1680+128 in this case). That is exactltly what the script does.

    Subsequently, the found numbers are used as arguments to run the xdotool mousemove-command.


In Ubuntu 18.04 there are no custom shortcuts, so following @JacobVlijm's approach, I calculated my centers and wrote aliases in my shell:

sudo echo -e "\
alias lt='xdotool mousemove 640 360' \n\  # lt means left
alias rt='xdotool mousemove 1920 512'\   # rt means right
" >> .bashrc