我想为Mac OS X编写一个简单的菜单栏应用程序。用户只想在打开Safari时使用该应用程序。为了不会不必要地混淆菜单栏,我想隐藏并显示菜单栏图标,具体取决于Safari是否开放。
我的应用可能会注册一些通知吗?我能想象的唯一解决方法是轮询正在运行的进程并查看Safari是否已启动,但这似乎不是解决我问题的优雅方法......
答案 0 :(得分:3)
NSWorkspaceDidLaunchApplicationNotification
和NSWorkspaceDidTerminateApplicationNotification
。 (有相同的碳事件。)
答案 1 :(得分:1)
使用kEventAppFrontSwitched in Carbon Event Manager在其他应用程序变为活动状态时收到通知。
答案 2 :(得分:0)
使用以下代码: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()
行。
答案 3 :(得分:0)
遇到同样的问题,但多亏了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
}
}