如何检测某个应用程序何时打开?

时间:2013-02-19 21:49:59

标签: objective-c macos applescript

在Applescript或Objective-C中,有没有办法检测某个应用程序何时打开?我的目标是为我正在处理的应用程序添加一个功能,以便在“QuickTime Player”打开时显示消息,但我没有在Apple开发人员文档中找到任何显示如何执行此操作的内容。< / p>

1 个答案:

答案 0 :(得分: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.
}

希望有所帮助。