【发布时间】:2010-10-20 06:21:58
【问题描述】:
我希望在当前应用程序发生更改时收到通知。我看了看 NSWorkspace。只有当您自己的应用程序激活或失去活动时,它才会发送通知。 我想了解每个应用程序。如何在 Cocoa 中做到这一点?
【问题讨论】:
-
不可能从 Cocoa 获得这些信息。您必须使用 Carbon 事件管理器来获取有关您自己以外的进程何时激活的通知。
标签: cocoa
我希望在当前应用程序发生更改时收到通知。我看了看 NSWorkspace。只有当您自己的应用程序激活或失去活动时,它才会发送通知。 我想了解每个应用程序。如何在 Cocoa 中做到这一点?
【问题讨论】:
标签: cocoa
如果您的目标是 10.6 或更高版本,则会收到通知:
// NSWorkspaceDidActivateApplicationNotification
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(foremostAppActivated:) name:NSWorkspaceDidActivateApplicationNotification object:nil];
【讨论】:
- (void)foremostAppActivated:(NSNotification *)notification
谢谢杰森。 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;
}
【讨论】: