applescriptでメニューバーに触りたい
applescriptというものを知ったので、早速使ってみようと思ったんだけど、これが一向によくわからない。
そもそもネットの情報が断片的で、多いとは言えない。
目的のコードは乗っているが、何がなんだかわからないという状態が続いたけど、よくわからなかった部分がわかりかけているのでメモ。
以下bluetoothをオンにして、自動的に目的のデバイスと接続するスクリプト。
よくわからなかったのは、メニューの階層構造をapplescriptでどう扱うのかという部分だった。
bluetoothは、
SystemUIServerというプロセスのmenu bar 1 にある。
これをクリックすると、接続状態や接続するデバイスが表示される。
これは menu items of menu bar 1 で表現される。
特定のアイテムが欲しい場合は menu item "名前" of menu bar 1 と記述する。
これによってクリック等が可能になる。
さらにしたのメニューに行く場合、(bluetoothの例)
menu item "接続" of menu "デバイスの名前" of menu item "デバイスの名前" of menu bar item 7(bluetoothのインデックス)
という感じになる。
つまり、(そのメニューのアイテム of 親メニュー) of menu item ... って感じ。
このof地獄がいい書き方なのかは自信がないが他のやり方がわからない...
#!/usr/bin/osascript tell application "System Events" tell process "SystemUIServer" -- bluetoothのオブジェクトをbtに格納する(以後、記述を簡略化するため。) set bt to (menu bar item 1 of menu bar 1 whose description contains "bluetooth") tell bt -- まず開かないとダメ。その後のメニューはクリックできない click it try click menu item "Bluetoothをオンにする" of menu 1 delay 2 on error --click menu item "Bluetoothをオフにする" of menu 1 end try click it -- クリックして進むたびに if exists menu item "(デバイスの名前)" of menu 1 then click menu item "(デバイスの名前)" of menu 1 click menu item "接続" of menu "(デバイスの名前)" of menu item "(デバイスの名前)" of menu 1 end if end tell end tell end tell