LoginSignup
0
2

More than 5 years have passed since last update.

Cocoaの機能を使ってメニューバーアプリケーションの使用をきっかけに動作するAppleScriptアプリケーションサンプル

Posted at
  • スクリプトエディタで下のコードを保存
    • ファイルフォーマット:アプリケーション
    • オプション:「ハンドラの実行後に終了しない」にチェック
  • 通常のアプリケーションとして実行
    • 起動後は何も動作しないように見える
    • 通常のアプリケーションと同様、command + Qなどで終了
  • メニューバーアプリケーションを使用するとnotifyハンドラが実行される
    • アプリケーションが起動している間は何回でも繰り返し実行される
  • notifyハンドラ内で動作内容を決める
    • ifから始まる行の"com.google.musicmanager"を、動作のきっかけとなる別のメニューバーアプリケーションのバンドルIDに変更
    • delay 3の行からが動作内容のメイン部分
triggeredByUsingMenuBarApplication.app
use scripting additions
use framework "AppKit"
use framework "Foundation"

on run
    --NSDistributedNotificationCenterに"com.apple.HIToolbox.beginMenuTrackingNotification"という通知があったとき、このAppleScript内の"notify:"ハンドラを実行するobserverを追加
    current application's NSDistributedNotificationCenter's defaultCenter()'s addObserver:me selector:"notify:" |name|:"com.apple.HIToolbox.beginMenuTrackingNotification" object:(missing value)
end run

on quit
    --アプリケーション終了時、runハンドラでNSDistributedNotificationCenterに追加したobserverを削除
    current application's NSDistributedNotificationCenter's defaultCenter()'s removeObserver:me
    continue quit
end quit

on notify:notification
    --メニューバーアプリケーションのバンドルIDが"com.google.musicmanager"かどうかチェック
    set notifiedApplication to current application's NSRunningApplication's runningApplicationWithProcessIdentifier:(notification's userInfo's ToolboxMessageEventData)
    if (notifiedApplication's bundleIdentifier's isEqual:"com.google.musicmanager") as boolean then

        --3秒待ってダイアログ表示
        delay 3
        activate
        display dialog (notifiedApplication's localizedName as text) & " is being used" buttons {"OK"} default button 1

    end if
end notify:

更新履歴

  • 2016-10-07: FoundationフレームワークのNSDistributedNotificationCenterクラスを使って作成
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2