我希望在当前应用程序更改时收到通知。我查看了NSWorkspace,但它只会在自己的应用程序变为活动状态或失去活动状态时发送通知。 我想要关于每个应用程序的信息。在Cocoa中我该如何做到这一点?
我希望在当前应用程序更改时收到通知。我查看了NSWorkspace,但它只会在自己的应用程序变为活动状态或失去活动状态时发送通知。 我想要关于每个应用程序的信息。在Cocoa中我该如何做到这一点?
如果你的目标系统是10.6或更高版本,则可以使用通知来实现此功能:
// NSWorkspaceDidActivateApplicationNotification
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(foremostAppActivated:) name:NSWorkspaceDidActivateApplicationNotification object:nil];
- (void)foremostAppActivated:(NSNotification *)notification
- mrwalker谢谢Jason。Carbon事件管理器中的kEventAppFrontSwitched是解决问题的关键。
- (void) setupAppFrontSwitchedHandler
{
EventTypeSpec spec = { kEventClassApplication, kEventAppFrontSwitched };
OSStatus err = InstallApplicationEventHandler(NewEventHandlerUPP(AppFrontSwitchedHandler), 1, &spec, (void*)self, NULL);
if (err)
NSLog(@"Could not install event handler");
}
- (void) appFrontSwitched {
NSLog(@"%@", [[NSWorkspace sharedWorkspace] activeApplication]);
}
处理程序
static OSStatus AppFrontSwitchedHandler(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{
[(id)inUserData appFrontSwitched];
return 0;
}