How to set cursor position with command/script?
I have a script which resets some things, and at the end of it I need it to set the cursor to certain coordinates, either to a custom set or to the centre of the screen (where it is reset to by default when restarting gnome-shell
for instance).
How can this be achieved? The solution would have to work for all display sizes and be able to automatically get the data and do all the maths etc involved.
I am running Ubuntu GNOME 16.04 with GNOME 3.20.
Moving the mouse to a defined (absolute) position
..is simply done by the command (e.g.):
xdotool mousemove 200 200
To move the mouse to the centre of the screen however is a relative command, for which we need to read the screen's information and do some calculations. This is done in the two small scripts below.
Straightforward version (move cursor to the center of the left screen)
To move the mouse to the center of the (leftmost) screen, use the script below:
#!/usr/bin/env python3
import subprocess
xr = [s for s in subprocess.check_output("xrandr").decode("utf-8").split() if "+0+" in s]
scr = [int(n)/2 for n in xr[0].split("+")[0].split("x")]
subprocess.Popen(["xdotool", "mousemove", str(scr[0]), str(scr[1])])
-
install xdotool
sudo apt-get install xdotool
Copy the script into an empty file, save it as
center_screen.py
-
Run it:
python3 /path/to/center_screen.py
Extended version (optional arguments x, y)
If arbitrary coordinates are optional, use:
#!/usr/bin/env python3
import subprocess
import sys
if sys.argv[1:]:
scr = [sys.argv[1], sys.argv[2]]
else:
xr = [s for s in subprocess.check_output("xrandr").decode("utf-8").split() if "+0+" in s]
scr = [str(int(n)/2) for n in xr[0].split("+")[0].split("x")]
subprocess.Popen(["xdotool", "mousemove", scr[0], scr[1]])
This version will move the cursor to the center of the screen, when run without arguments, or to an arbitrary position, when run with arguments, e.g.:
python3 /path/to/center_screen.py 200 200
Explanation
In the output of the command: xrandr
, all we need to find is the string like:
1680x1050+0+0
...which contains the data on the leftmost screen (+0+
). both figures in 1680x1050
are then to be divided by two, to be used in:
xdotool mousemove <x> <y>
The line:
if sys.argv[1:]:
is then to decide wether the given arguments should be used or the calculated ones.