新手在这里。我正在尝试为应用程序启动创建一个小型侦听器,而我已经有了这个:
// almon.m
#import <Cocoa/Cocoa.h>
#import <stdio.h>
#include <signal.h>
@interface almon: NSObject {}
-(id) init;
-(void) launchedApp: (NSNotification*) notification;
@end
@implementation almon
-(id) init {
NSNotificationCenter * notify
= [[NSWorkspace sharedWorkspace] notificationCenter];
[notify addObserver: self
selector: @selector(launchedApp:)
name: @"NSWorkspaceWillLaunchApplicationNotification"
object: nil
];
fprintf(stderr,"Listening...\n");
[[NSRunLoop currentRunLoop] run];
fprintf(stderr,"Stopping...\n");
return self;
}
-(void) launchedApp: (NSNotification*) notification {
NSDictionary *userInfo = [notification userInfo]; // read full application launch info
NSString* AppPID = [userInfo objectForKey:@"NSApplicationProcessIdentifier"]; // parse for AppPID
int killPID = [AppPID intValue]; // define integer from NSString
kill((killPID), SIGSTOP); // interrupt app launch
NSString* AppPath = [userInfo objectForKey:@"NSApplicationPath"]; // read application path
NSString* AppBundleID = [userInfo objectForKey:@"NSApplicationBundleIdentifier"]; // read BundleID
NSString* AppName = [userInfo objectForKey:@"NSApplicationName"]; // read AppName
NSLog(@":::%@:::%@:::%@:::%@", AppPID, AppPath, AppBundleID, AppName);
}
@end
int main( int argc, char ** argv) {
[[almon alloc] init];
return 0;
}
// build: gcc -Wall almon.m -o almon -lobjc -framework Cocoa
// run: ./almon
注意:构建它时,它将运行良好,但是如果在High Sierra上使用Xcode 10进行操作,则会收到ld
警告,但是您可以忽略该警告。
我的问题:是否有办法检测后台应用程序的启动,例如粘度等菜单栏应用程序?苹果说
系统不发布 [NSWorkspaceWillLaunchApplicationNotification]用于后台应用程序或 适用于
LSUIElement
文件中具有Info.plist
键的应用。 如果您想知道所有应用程序(包括后台应用程序)何时 启动或终止,请使用键值观察来监视值 由runningApplications
方法返回。
我至少会尝试向侦听器添加对后台应用程序等的支持,但是我不知道该怎么做。有什么想法吗?
答案 0 :(得分:1)
如文档所建议,您可以使用键值观察来观察共享工作区对象的runningApplications
属性:
static const void *kMyKVOContext = (void*)&kMyKVOContext;
[[NSWorkspace sharedWorkspace] addObserver:self
forKeyPath:@"runningApplications"
options:NSKeyValueObservingOptionNew // maybe | NSKeyValueObservingOptionInitial
context:kMyKVOContext];
然后,您将实现观察方法(使用Xcode的现成代码段):
- (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#>
}
}