Mac OS X-监视应用程序启动?
-
02-10-2019 - |
题
我想为Mac OS X编写一个简单的Menubar应用程序。用户只想在打开Safari时使用该应用程序。为了不必要地杂乱无章,我想根据野生动物园是否开放,隐藏并展示梅巴尔图标。
是否有一些通知我的应用程序可以注册?我能想象的唯一解决方法是调查运行过程,看看是否启动了野生动物园,但这似乎不是解决我的问题的优雅方法...
解决方案
NSWorkspaceDidLaunchApplicationNotification
和 NSWorkspaceDidTerminateApplicationNotification
. 。 (有等效的碳事件。)
其他提示
采用 KeventappFrontswitch在碳活动经理中 在其他应用程序处于活动状态时获取通知。
使用此代码: http://cl.ly/2LBB
// usleep(40500);
ProcessNotif * x = [[ProcessNotif new] autorelease];
[x setProcessName: @"Safari"];
[x setTarget: self];
[x setAction: @selector(doStuff)];
[x start];
这将运行选择器 -doStuff
当野生动物园运行时。如果您有错误,请输入 usleep()
线。
遇到了同样的问题,但感谢JWWALKER,Documentation和Google编写了此代码:
// 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
}
}
不隶属于 StackOverflow