How to get the current monitor resolution or monitor name (LVDS, VGA1, etc)
I would like to get the resolution of the current monitor (the screen from where I run the script) or the name of the screen (LVDS, VGA1, etc).
If I can't get the resolution but only the monitor name, I could grep 'xrandr -q' output to get current resolution.
Thanks in advance.
You should be able to do this by a combination of xrandr
and xwininfo
.
-
Get the screens, their resolutions and offsets:
$ xrandr | grep -w connected | awk -F'[ \+]' '{print $1,$3,$4}' VGA-0 1440x900 1600 DP-3 1600x900 0
-
Get the position of the current window
$ xwininfo -id $(xdotool getactivewindow) | grep Absolute Absolute upper-left X: 1927 Absolute upper-left Y: 70
So, by combining the two you should be able to get the resolution of the current screen:
#!/usr/bin/env bash
## Get screen info
screen1=($(xrandr | grep -w connected | awk -F'[ +]' '{print $1,$3,$4}' |
head -n 1))
screen2=($(xrandr | grep -w connected | awk -F'[ +]' '{print $1,$3,$4}' |
tail -n 1))
## Figure out which screen is to the right of which
if [ ${screen1[2]} -eq 0 ]
then
right=(${screen2[@]});
left=(${screen1[@]});
else
right=(${screen1[@]});
left=(${screen2[@]});
fi
## Get window position
pos=$(xwininfo -id $(xdotool getactivewindow) | grep "Absolute upper-left X" |
awk '{print $NF}')
## Which screen is this window displayed in? If $pos
## is greater than the offset of the rightmost screen,
## then the window is on the right hand one
if [ "$pos" -gt "${right[2]}" ]
then
echo "${right[0]} : ${right[1]}"
else
echo "${left[0]} : ${left[1]}"
fi
The script will print the name and resolution of the current screen.
Here is a version I hacked together in Python that is based on GTK and does not rely on (parsing the output of) command line tools.
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk
disp=Gdk.Display.get_default()
scr=disp.get_default_screen()
win_pos=scr.get_active_window().get_origin()
print("win: %d x %d" % (win_pos.x, win_pos.y))
rect=disp.get_monitor_at_point(win_pos.x, win_pos.y).get_geometry()
print("monitor: %d x %d" % (rect.width, rect.height))