0

我想为 Mac OS X 编写一个简单的菜单栏应用程序。用户只想在 Safari 打开时使用该应用程序。为了避免不必要地弄乱菜单栏,我想根据 Safari 是否打开来隐藏和显示菜单栏图标。

是否有一些通知可以让我的应用注册?我能想象的唯一解决方法是轮询正在运行的进程并查看是否启动了 Safari,但这似乎不是解决我的问题的一种优雅方式......

4

4 回答 4

3

NSWorkspaceDidLaunchApplicationNotificationNSWorkspaceDidTerminateApplicationNotification。(有等效的碳事件。)

于 2010-09-12T18:41:48.030 回答
1

使用Carbon Event Manager 中的 kEventAppFrontSwitched 在另一个应用程序激活时获取通知。

于 2010-09-12T15:11:40.417 回答
0

使用此代码:http ://cl.ly/2LbB

// usleep(40500);

ProcessNotif * x = [[ProcessNotif new] autorelease];
[x setProcessName: @"Safari"];
[x setTarget: self];
[x setAction: @selector(doStuff)];
[x start];

这将-doStuff在 Safari 运行时运行选择器。如果出现错误,请取消注释该usleep()行。

于 2010-09-12T15:24:47.080 回答
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
    }
}
于 2013-09-02T16:42:44.983 回答