获取其他应用的所有快捷方式列表
我在想有没有简单的方法可以获取其他应用程序菜单栏中所有的快捷键列表(如果可能的话,也包括已经关闭的应用程序)。
我想在我正在写的一个简单的Python应用程序中使用这个功能,以便简化我为不同应用程序配置Wacom平板的过程。其实不需要特别“干净”的解决方案,只要能生成一次列表,然后再把它读入我的程序就行。
我之前玩过AppleScript,所以如果能通过AppleScript来实现,那就更好了。
2 个回答
0
do shell script "date '+%T' > /0/ase.txt"
set proc to "AppleScript Editor"
tell application "System Events" to tell process proc
set out to ""
set v to menu bar item 4 of menu bar 1
-- repeat with v in menu bar items 2 thru -1 of menu bar 1
set out to out & name of v & linefeed
repeat with w in menu items of menu 1 of v
set out to out & " " & my getshortcut(proc, w) & " " & name of w & linefeed
try
repeat with x in menu items of menu 1 of w
set out to out & " " & my getshortcut(proc, x) & " " & name of x & linefeed
end repeat
end try
end repeat
-- end repeat
end tell
on getshortcut(proc, x)
set text item delimiters to space
set menuglyphs to text items of "2 ⇥ 3 ⇤ 4 ⌤ 9 ␣ 10 ⌦ 11 ↩ 16 ↓ 23 ⌫ 24 ← 25 ↑ 26 → 27 ⎋ 28 ⌧ 98 ⇞ 99 ⇪ 100 ← 101 → 102 ↖ 104 ↑ 105 ↘ 106 ↓ 107 ⇟ 111 F1 112 F2 113 F3 114 F4 115 F5 116 F6 117 F7 118 F8 119 F9 120 F10 121 F11 122 F12 135 F13 136 F14 137 F15 140 ⏏ 143 F16 144 F17 145 F18 146 F19"
set cmdmods to text items of "⌘ ⇧⌘ ⌥⌘ ⌥⇧⌘ ⌃⌘ ⌃⇧⌘ ⌃⌥⌘ ⌃⌥⇧⌘ - ⇧ ⌥ ⌥⇧ ⌃ ⌃⇧ ⌃⌥ ⌃⌥⇧"
tell application "System Events" to tell process proc
set c to ""
try
set n to value of attribute "AXMenuItemCmdModifiers" of x
set modifier to item (n + 1) of cmdmods
try
set c to (value of attribute "AXMenuItemCmdChar" of x)
c as text
return modifier & c
on error
set glyph to (value of attribute "AXMenuItemCmdGlyph" of x) as text
repeat with i from 1 to (count menuglyphs)
if item i of menuglyphs is glyph then
return modifier & item (i + 1) of menuglyphs
end if
end repeat
end try
end try
return "-"
end tell
end getshortcut
do shell script "echo " & quoted form of out & "`date '+%T'` >> /0/ase.txt"
out
这个运行得真慢(整个脚本在我电脑上大约需要3到10分钟才能完成),不过至少它勉强能工作。
3
你可能需要使用图形用户界面(gui)脚本,这意味着你得先打开应用程序。我试过在Safari上这样做。如果你查看“文件”菜单,第六个选项是“关闭窗口”,它的快捷键是shift-cmd-w。我专门关注了这个选项,看看能不能获取到它...
tell application "System Events"
tell process "Safari"
-- get the menu bar items from the main menu
tell menu bar 1
set menuBarItems to menu bar items -- apple menu, application menu, file menu etc.
end tell
-- get the menu items from a menu bar item
set fileMenuBarItem to item 3 of menuBarItems -- the file menu
tell menu 1 of fileMenuBarItem -- you have to have "menu 1" here
set menuItems to menu items
end tell
-- query the menu bar item
set closeWindowMenuItem to item 6 of menuItems -- close window menu item
tell closeWindowMenuItem
return {name, value} of attributes
end tell
end tell
end tell
如果你查看结果,会发现这个菜单项有几个有趣的属性。它有一个叫“AXMenuItemCmdChar”的属性,这个属性告诉我快捷键中的“w”。所以我们知道“cmd-w”是这个快捷键的一部分。还有一个叫“AXMenuItemCmdModifiers”的属性,它的值是1。这应该就是shift键。
所以看起来你可以自己搞明白。这就是我所做的,你需要进一步研究一下,看看是否需要其他属性。你还需要添加重复循环,这样才能遍历每一个菜单项。
我注意到的一件事是……如果你打开文件菜单并按下“option”键,你会发现菜单项会发生变化。这些变化后的菜单项在你获取菜单栏项的菜单项时也会出现。所以你并不总能看到你将要获取的菜单项。