2013-02-19 68 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

相关问题