メニュー項目が表すオブジェクトや機能への直接アクセスを AppleScript ライブラリが提供しないアプリケーションのメニュー項目にアクセスするための GUI スクリプトを頻繁に作成する必要があります。コードを簡単に再利用できるように、アプリ、メニュー、およびメニュー項目の名前に変数を使用します。次に、コード本体から名前を選択するのではなく、上部の変数を変更するだけです。
set targetApp to "app_name"
set theMenu to "menu_name"
set theItem to "menu_item_name"
tell application targetApp
activate
tell application "System Events"
tell application process targetApp
tell menu bar 1
tell menu bar item theMenu
tell menu theMenu
click menu item theItem
end tell
end tell
end tell
end tell
end tell
end tell
サブメニュー
サブメニューとサブサブメニューが関係している場合は、もう少し複雑になります。サブメニューを持つメニュー項目は、その親メニューのメニュー項目であり、そのサブメニューのメニュー親でもあるためです。テキスト変数「theItem」は、メニュー項目とメニューの両方を指定するために使用されることに注意してください。「targetApp」文字列変数は、アプリとプロセスの両方を参照するために使用されるため、コードを再利用するときに、2 つの名前をそれぞれ 2 か所で編集する必要がなくなります。このスクリプトを使用して、メニュー項目にすばやくアクセスするための音声コマンドを実行します。たとえば、「[メニューの編集] をクリックしてください」...「変換をクリックしてください」...「[大文字にする] をクリックしてください」... 別の変数を追加しますサブメニュー項目の場合:
set targetApp to "app_name"
set theMenu to "menu_name"
set theItem to "menu_item_name"
set theSubItem to "sub_item_name"
tell application targetApp
activate
tell application "System Events"
tell application process targetApp
tell menu bar 1
tell menu bar item theMenu
tell menu theMenu
tell menu item theItem
tell menu theItem
click menu item theSubItem
end tell
end tell
end tell
end tell
end tell
end tell
end tell
end tell
例えば:
set targetApp to "TextEdit"
set theMenu to "Edit"
set theItem to "Transformations"
set theSubItem to "Make Upper Case"
tell application targetApp
activate
tell application "System Events"
tell application process targetApp
tell menu bar 1
tell menu bar item theMenu
tell menu theMenu
tell menu item theItem
tell menu theItem
click menu item theSubItem
end tell
end tell
end tell
end tell
end tell
end tell
end tell
end tell
別のレベルのサブメニューがある場合は、追加の変数 (「theSubSubItem」など) が必要になり、システム イベント プロセスの Tell ブロックの行に別のレイヤーが含まれ
ます ...
tell menu item theItem
tell menu theSubItem
click menu item theSubSubItem
end tell
end tell
...
このスレッドの他の場所で述べたように、アプリケーションのオブジェクトと関数が API に含まれている場合は常にそれらに直接対処することをお勧めしますが、GUI に対処することは、API が直接アクセスを提供しない場合の最後の手段として役立ちます。欠点は、GUI スクリプトが煩雑になり、アプリケーションの更新ごとに修正が必要になる可能性があることです。