wmctrl 無法在腳本內調整視窗大小/移動視窗

wmctrl 無法在腳本內調整視窗大小/移動視窗

我正在嘗試編寫一個腳本來打開一堆程式並移動/調整螢幕上的視窗大小。

例如,

#!/bin/bash
zim
wmctrl -r Zim -b toggle,maximized_vert
wmctrl -r Zim -e 0,700,0,-1,-1

我運行這個腳本,視窗最大化並向右移動了一點。但是,如果我替換zimfirefoxacroread,則無法移動/調整視窗大小。

wmctrl如果我在終端中輸入它確實可以工作,但是,我想要它在腳本裡面。我認為這一定與firefox記住它在螢幕上的位置的方式有關。

編輯:我放置了

firefox
wmctrl -lG

在腳本中,我得到以下輸出:

0x03800032  0 1168 347  750  731  briareos emacs@briareos
0x02a00002  0 -2020 -1180 1920 1080 briareos XdndCollectionWindowImp
0x02a00005  0 0    24   47   1056 briareos unity-launcher
0x02a00008  0 0    0    1920 24   briareos unity-panel
0x02a0000b  0 -420 -300 320  200  briareos unity-dash
0x02a0000c  0 -420 -300 320  200  briareos Hud
0x03c00011  0 59   52   900  1026 briareos Notes - Zim

這意味著該腳本不知道 Firefox 已啟動。

答案1

問題

問題是,在您使用的命令組合中,您需要“幸運”才能及時顯示應用程式的窗口,命令wmctrl才能成功。
您的命令可能在大多數情況下適用於輕型應用程序,啟動速度很快,但在其他應用程式(例如 Inkscape、Firefox 或 Thunderbird)上可能會中斷。

內建5 或10 秒的中斷,就像你所做的那樣(在評論中提到),但是要么你必須等待比必要的時間更長的時間,要么如果你的處理器被佔用並且窗口“比平時晚”,它最終會中斷。

解決方案

解決方案是在腳本中包含一個過程,等待視窗出現在 的輸出中wmctrl -lp,然後執行命令以最大化視窗。

python下面的範例中,我曾經調整視窗大小,根據我的經驗,這比完成這項工作xdotool更強大:wmctrl

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

app = sys.argv[1]

# to only list processes of the current user
user = getpass.getuser()
get = lambda x: subprocess.check_output(x).decode("utf-8")
# get the initial window list
ws1 = get(["wmctrl", "-lp"]); t = 0
# run the command to open the application
subprocess.Popen(app)

while t < 30:
    # fetch the updated window list, to see if the application's window appears
    ws2 = [(w.split()[2], w.split()[0]) for w in get(["wmctrl", "-lp"]).splitlines() if not w in ws1]
    # see if possible new windows belong to our application
    procs = sum([[(w[1], p) for p in get(["ps", "-u", user]).splitlines() \
              if app[:15].lower() in p.lower() and w[0] in p] for w in ws2], [])
    # in case of matches, move/resize the window
    if len(procs) > 0:
        subprocess.call(["xdotool", "windowsize", "-sync", procs[0][0] , "100%", "100%"])
        break
    time.sleep(0.5)
    t = t+1

如何使用

  1. 該腳本需要wmctrlxdotool

    sudo apt-get install wmctrl xdotool
    
  2. 將腳本複製到一個空文件中,另存為resize_window.py

  3. 測試 - 使用應用程式作為參數來運行腳本,例如:

    python3 /path/to/resize_window.py firefox
    

筆記

  • 如果您將其用作啟動應用程式中的腳本,則獲取視窗清單的命令很可能wmctrl會過早運行。如果您遇到問題,我們需要為整個過程添加一個try/ 。except如果是這樣,請告訴我。

相關內容