menu E4b9a6's blog
rss_feed
E4b9a6's blog
有善始者实繁,能克终者盖寡。

Linux下启动和激活程序窗体

作者:E4b9a6, 创建:2024-09-11, 字数:1913, 已阅:66, 最后更新:2024-09-11

xtools 用于管理和处理 X11 应用程序窗口的工具,支持 GNOME 、 KDE Plasma、 XFCE 等常见桌面环境

在Linux下开发时,设置全局快捷键在不同的程序之间切换可以有效提高效率

但直接将快捷键绑定到对应程序路径,会导致每次按下快捷键都是启动新的程序实例,这对于文件资源管理器、浏览器来说不友好

借助 xtools 就可以实现按下快捷键激活已运行的程序窗体在前台,在 debian 中,安装 xtools 如下:

Bash
sudo apt install xtools

实现的方法如下:

Bash
#!/bin/bash
#author:chancel.yang
#date:2024-09-11

# Check the number of parameters
if [ "$#" -ne 2 ]; then
    echo "Usage: bash xtoold.sh <classname> <program_path>"
    exit 1
fi

# Get the input parameters
CLASSNAME="$1"
PROGRAM_PATH="$2"

echo "Provided class name: $CLASSNAME"
echo "Provided program path: $PROGRAM_PATH"

# Get the current desktop ID
DESKTOP_ID=$(xdotool get_desktop)
echo "Current desktop ID: $DESKTOP_ID"

# Find program window IDs
WINDOW_IDS=$(xdotool search --desktop "$DESKTOP_ID" --class "$CLASSNAME")
echo "Found window ID(s): $WINDOW_IDS"

# Check the returned IDs
if [ -n "$WINDOW_IDS" ]; then
    # Get the last ID
    LAST_WINDOW_ID=$(echo "$WINDOW_IDS" | tail -n 1)
    echo "Last window ID: $LAST_WINDOW_ID"

    # Activate the program window
    echo "Activating program window..."
    xdotool windowactivate "$LAST_WINDOW_ID"
    echo "Program window has been activated."
else
    # If no ID is found, start the program
    echo "No window found, preparing to start the program..."
    if [ -x "$PROGRAM_PATH" ]; then
        echo "Starting program: $PROGRAM_PATH"
        "$PROGRAM_PATH" &
        echo "Program has been started."
    else
        echo "Error: Cannot find executable program path: $PROGRAM_PATH"
        exit 1
    fi
fi

脚本传入参数说明:

  • $1是程序的 classname, 可以通过 xprop | grep WM_CLASS 选定窗体后得到
  • $2是当程序没有处于运行状态时,运行新程序的路径

将以上脚本保存到 /path/xtools.sh ,在 系统设置-全局快捷键 中添加按下 Win+G 执行脚本:

Bash
/bin/bash /path/xtools.sh google-chrome /usr/bin/google-chrome-stable

系统设置截图如下:

设置完毕后,按下 Win+G ,Chrome 将从后台被激活到前台,上述脚本可以设置为任何快捷键激活指定的程序窗体


[[replyMessage== null?"发表评论":"发表评论 @ " + replyMessage.m_author]]

account_circle
email
web_asset
textsms

评论列表([[messageResponse.total]])

还没有可以显示的留言...
gravatar
[[messageItem.m_author]] [[messageItem.m_author]]
[[messageItem.create_time]]
[[getEnviron(messageItem.m_environ)]]
[[subMessage.m_author]] [[subMessage.m_author]] @ [[subMessage.parent_message.m_author]] [[subMessage.parent_message.m_author]]
[[subMessage.create_time]]
[[getEnviron(messageItem.m_environ)]]