2013-02-19 88 views
0

在Applescript或Objective-C中,有一種方法可以檢測某個應用程序何時打開?我的目標是在我打算在每當「QuickTime Player」打開時顯示消息的應用程序中添加一項功能,但是我沒有在Apple開發人員文檔中找到任何顯示如何執行此操作的任何內容。如何檢測某個應用程序何時打開?

回答

2

這對Objective-C非常簡單。下面的代碼:

註冊適當的通知從NSWorkspace

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    //Fetch the notification center from the workspace 
    NSNotificationCenter* center = [[NSWorkspace sharedWorkspace] notificationCenter]; 

    [center addObserver:self selector:@selector(newApplicationDidLaunch:) name:NSWorkspaceDidLaunchApplicationNotification object:nil]; 

    [center addObserver:self selector:@selector(newApplicationWillLaunch:) name:NSWorkspaceWillLaunchApplicationNotification object:nil]; 

} 

然後,添加您選擇的通知。通知的userInfo字典將包含您需要知道的所有內容:

-(void)newApplicationDidLaunch:(NSNotification*)notification { 

    NSDictionary* userInfo = notification.userInfo; 
    //Do what you want here after application launch. 
} 

-(void)newApplicationWillLaunch:(NSNotification*)notification { 

    NSDictionary* userInfo = notification.userInfo; 
    //Do what you want here to prepare for application launch. 
} 

希望有所幫助。

+0

這太好了。只有一件事:'userInfo'是否包含應用程序的名稱? – pasawaya 2013-02-19 22:19:14

+0

是的。它可以通過'NSApplicationName'鍵進行訪問。 – 2013-02-19 22:46:56

相關問題