如何使用命令/脚本设置光标​​位置?

7 command-line scripts cursor screen xdotool

我有一个脚本可以重置一些东西,最后我需要它把光标设置到特定的坐标,要么是自定义集,要么是屏幕中心(gnome-shell例如,在重新启动时它默认重置为)。

如何做到这一点?该解决方案必须适用于所有显示尺寸,并能够自动获取数据并进行所有涉及的数学运算等。

我正在使用 GNOME 3.20 运行 Ubuntu GNOME 16.04。

Jac*_*ijm 9

将鼠标移动到定义的(绝对)位置

.. 简单地由命令完成(例如):

xdotool mousemove 200 200
Run Code Online (Sandbox Code Playgroud)

然而,将鼠标移动到屏幕中心是一个相对命令,我们需要读取屏幕信息并进行一些计算。这是在下面的两个小脚本中完成的。

简单版本(将光标移动到左侧屏幕的中心)

要将鼠标移动到(最左侧)屏幕的中心,请使用以下脚本:

xdotool mousemove 200 200
Run Code Online (Sandbox Code Playgroud)

扩展版本(可选参数 x, y)

如果任意坐标是可选的,请使用:

#!/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])])
Run Code Online (Sandbox Code Playgroud)

此版本将光标移动到屏幕的中心,运行时不带参数,或移动到任意位置,运行时带参数,例如:

python3 /path/to/center_screen.py 200 200
Run Code Online (Sandbox Code Playgroud)

解释

在命令的输出中:xrandr,我们需要找到的只是像这样的字符串:

1680x1050+0+0
Run Code Online (Sandbox Code Playgroud)

...其中包含最左侧屏幕 ( +0+)上的数据。1680x1050然后将两个数字 除以二,用于:

xdotool mousemove <x> <y>
Run Code Online (Sandbox Code Playgroud)

线路:

if sys.argv[1:]:
Run Code Online (Sandbox Code Playgroud)

然后决定是应该使用给定的参数还是计算出来的参数。