[ubuntu]使用快捷键启动或切换到某个程序

用快捷键启动某个程序是很简单的事情,但是如果是下面的需求,就要麻烦一点
点击快捷键之后
1. 如果程序未启动,那么就启动程序
2. 如果程序已经启动,那么就切换到对应的程序.而且如果有多个同样的程序存在时,点击快捷键要可以在这些程序见循环的切换

google之后,找到两篇文章
Custom hotkey/shortcut to open/bring to front an app
Window Shortcuts for Linux

结合两篇文章中程序,对第二篇文章提供的程序根据自己的需求进行了小修改:

  • 支持按照程序名/程序标题栏名进行程序查找
  • 支持自定义的程序启动命令

编写如下的程序 /home/owen/bin/focus
[python]
#!/usr/bin/env python
import os
import sys
import commands

run_command = sys.argv[1] # the program to be run
program_name = sys.argv[2] # the program to be focused

# get all windows which contain "program_name" from wmcontrol
candidates = sorted([x.strip() for x in commands.getoutput(""" wmctrl -l -x | awk -v win="%s" 'tolower($0) ~ win {print $1;}' """ % (program_name, )).split("\n") if x !=''])

if candidates :
# at least one candidate found , we need to check if the active window is among the candidates (for cycling)

# Get the id of the active window

# Note: wmctrl currently does not support getting information about the active window. In order to realize this
# we use xprop here. Unfortunately xprop gives us the window id of the active window in a different format:
# Window ids from wmctrl always begin with 0x followed by 8 digits (leading zeroes for padding). xprop
# does not do the padding and might give a window id starting with 0x followed by only 6 digits. The
# lines below get the id of the current window and make the id returned by xprop comaptible with
# the window ids returned by wmctrl.
active_window_string = commands.getoutput("""xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)" """)
active_window_string = active_window_string[active_window_string.find("#")+4:].strip()
active_window = "0x" + "0" * (8-len(active_window_string)) + active_window_string

next_window = None # the window to display. (one of the windows in candidates)
if active_window not in candidates: # if the active window is not among the candidate windows
next_window = candidates[0] # ..just show the first candidate window
else:# we are already showing one of the candidate windows
next_window = candidates[ (candidates.index(active_window)+1) % len(candidates)] # show the *next* candidate in the list (cycling)

if next_window:
os.system(""" wmctrl -i -a "%s" """ % (next_window,) ) # tell wmcontrol to display the next_window
else : # no windows open which fit the pattern of program_name
os.system("%s &" % (run_command,)) # open new window
[/python]

把 win+c 快捷键绑定为
[shell]/home/owen/bin/focus gnome-terminal "terminal"[/shell]
那么, 点击 win+c 之后,就会自动启动gnome-terminal, 或者在多个已经启动的gnome-terminal中来回切换.


Last modified on 2011-02-13