Mac OS X - 监控应用程序启动?

我想为Mac OS X编写一个简单的菜单栏应用程序。用户只想在打开Safari时使用该应用程序。为了不会不必要地混淆菜单栏,我想隐藏并显示菜单栏图标,具体取决于Safari是否打开。 可能有一些我的应用程序可以注册的通知吗?我可以想象的唯一解决方法是轮询正在运行的进程并查看Safari是否已启动,但这似乎不是解决我的问题的优雅方式......     
已邀请:
NSWorkspaceDidLaunchApplicationNotification
NSWorkspaceDidTerminateApplicationNotification
。 (有相同的碳事件。)     
使用Carbon Event Manager中的kEventAppFrontSwitched在另一个应用程序变为活动状态时获取通知。     
使用以下代码:http://cl.ly/2LbB
// usleep(40500);

ProcessNotif * x = [[ProcessNotif new] autorelease];
[x setProcessName: @"Safari"];
[x setTarget: self];
[x setAction: @selector(doStuff)];
[x start];
当Safari运行时,这将运行选择器
-doStuff
。如果出现错误,请取消注释
usleep()
行。     
有同样的问题,但感谢JWWalker,文档和谷歌写了这段代码:
// i need to register on button event, you can do it even in applicationDidFinishLaunching
- (IBAction)Btn_LoginAction:(id)sender {
    ...
    NSNotificationCenter *center = [[NSWorkspace sharedWorkspace] notificationCenter];
    [center addObserver:self selector:@selector(appLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
    [center addObserver:self selector:@selector(appTerminated:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
}

// remember to unregister
- (void)ManageLogout:(NSInteger)aResult {
    ...
    NSNotificationCenter *center = [[NSWorkspace sharedWorkspace] notificationCenter];
    [center removeObserver:self name:NSWorkspaceDidLaunchApplicationNotification object:nil];
    [center removeObserver:self name:NSWorkspaceDidTerminateApplicationNotification object:nil];
}

- (void)appLaunched:(NSNotification *)note {
    [GTMLogger myLog:kGTMLoggerLevelDebug fmt:@"MainWinDelegate::appLaunched: %@ (%@)n", [[note userInfo] objectForKey:@"NSApplicationBundleIdentifier"], [[note userInfo] objectForKey:@"NSApplicationProcessIdentifier"]];

    if ( [[[note userInfo] objectForKey:@"NSApplicationBundleIdentifier"] isEqualToString:@"app.you.monitor.bundle.identifier"] ) {
        // do stuff
    }
}

- (void)appTerminated:(NSNotification *)note {
    [GTMLogger myLog:kGTMLoggerLevelDebug fmt:@"MainWinDelegate::appTerminated: %@ (%@)n", [[note userInfo] objectForKey:@"NSApplicationBundleIdentifier"], [[note userInfo] objectForKey:@"NSApplicationProcessIdentifier"]];

    if ( [[[note userInfo] objectForKey:@"NSApplicationBundleIdentifier"] isEqualToString:@"app.you.monitor.bundle.identifier"] ) {
        // do stuff
    }
}
    

要回复问题请先登录注册