macOS: Detect all application launches including background apps?

邮差的信 提交于 2019-12-06 18:14:27

As the document suggests, you use Key-Value Observing to observe the runningApplications property of the shared workspace object:

static const void *kMyKVOContext = (void*)&kMyKVOContext;


[[NSWorkspace sharedWorkspace] addObserver:self
                                forKeyPath:@"runningApplications"
                                   options:NSKeyValueObservingOptionNew // maybe | NSKeyValueObservingOptionInitial
                                   context:kMyKVOContext];

Then, you would implement the observation method (using Xcode's ready-made snippet):

- (void) observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
    if (context != kMyKVOContext)
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        return;
    }

    if ([keyPath isEqualToString:@"runningApplications"])
    {
        <#code to be executed when runningApplications has changed#>
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!