检测用户何时获取屏幕截图

时间:2010-12-23 08:01:51

标签: objective-c cocoa macos notifications

我正在寻找让我的应用在用户使用Command-Shift-3Command-Shift-4截取屏幕截图时收到通知的方式。

这方面的一个例子是Droplr和Cloud App等应用程序,可自动上传截图。

我一直在四处搜寻,发现它可能与Darwin Notifications有关,但我不确定从哪里开始。

3 个答案:

答案 0 :(得分:16)

之前的评论中提到了这一点,但您可以使用NSMetadataQuery搜索kMDItemIsScreenCapture = 1的文件。这是一个特殊属性,会添加到屏幕截图文件中。

我刚刚发了一个小演示,展示了如何做到并将其发布在github上:

https://github.com/davedelong/Demos/blob/master/ScreenShot%20Detector

答案 1 :(得分:3)

我就是这样做的,它有点复杂,但我会尝试逐步引导你:


在开始之前,在标题文件中声明以下变量和方法:

BOOL shouldObserveDesktop;
NSDictionary *knownScreenshotsOnDesktop;
NSString *screenshotLocation;
NSString *screenshotFilenameSuffix;

- (void)startObservingDesktop;
- (void)stopObservingDesktop;
- (NSDictionary *)screenshotsOnDesktop;
- (NSDictionary *)screenshotsAtPath:(NSString *)dirpath modifiedAfterDate:(NSDate *)lmod;
- (void)checkForScreenshotsAtPath:(NSString *)dirpath;
- (NSDictionary *)findUnprocessedScreenshotsOnDesktop;

现在在实施文件中,首先添加以下代码:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    screenshotLocation = [[NSString stringWithString:@"~/Desktop"] retain];
    screenshotFilenameSuffix = [[NSString stringWithString:@".png"] retain];
    knownScreenshotsOnDesktop = [[self screenshotsOnDesktop] retain];
    [self startObservingDesktop];
}

这会在调用所有方法时设置变量。接下来添加:

- (void)onDirectoryNotification:(NSNotification *)n {
    id obj = [n object];
    if (obj && [obj isKindOfClass:[NSString class]]) {
        [self checkForScreenshotsAtPath:screenshotLocation];
    }
}

- (void)startObservingDesktop {
    if (shouldObserveDesktop)
        return;
    NSDistributedNotificationCenter *dnc = [NSDistributedNotificationCenter defaultCenter];
    [dnc addObserver:self selector:@selector(onDirectoryNotification:) name:@"com.apple.carbon.core.DirectoryNotification" object:nil suspensionBehavior:NSNotificationSuspensionBehaviorDeliverImmediately];
    shouldObserveDesktop = YES;
}

- (void)stopObservingDesktop {
    if (!shouldObserveDesktop)
        return;
    NSDistributedNotificationCenter *dnc = [NSDistributedNotificationCenter defaultCenter];
    [dnc removeObserver:self name:@"com.apple.carbon.core.DirectoryNotification" object:nil];
    shouldObserveDesktop = NO;
}

在这里,我们观察在拍摄屏幕截图时将被调用的通知,并将其传递给要调用的方法(在本例中为onDirectoryNotification:)。还有一种方法可以停止观察桌面/通知。通知会调用checkForScreenshotsAtPath:,它会检查桌面上的屏幕截图。以下是该方法的代码以及它调用的其他方法:

-(void)checkForScreenshotsAtPath:(NSString *)dirpath {        
    NSDictionary *files;
    NSArray *paths;

    // find new screenshots
    if (!(files = [self findUnprocessedScreenshotsOnDesktop]))
        return;

    // sort on key (path)
    paths = [files keysSortedByValueUsingComparator:^(id a, id b) { return [b compare:a]; }];

    // process each file
    for (NSString *path in paths) {
        // Process the file at the path
    }
}

-(NSDictionary *)findUnprocessedScreenshotsOnDesktop {
    NSDictionary *currentFiles;
    NSMutableDictionary *files;
    NSMutableSet *newFilenames;

    currentFiles = [self screenshotsOnDesktop];
    files = nil;

    if ([currentFiles count]) {
        newFilenames = [NSMutableSet setWithArray:[currentFiles allKeys]];
        // filter: remove allready processed screenshots
        [newFilenames minusSet:[NSSet setWithArray:[knownScreenshotsOnDesktop allKeys]]];
        if ([newFilenames count]) {
            files = [NSMutableDictionary dictionaryWithCapacity:1];
            for (NSString *path in newFilenames) {
                [files setObject:[currentFiles objectForKey:path] forKey:path];
            }
        }
    }

    knownScreenshotsOnDesktop = currentFiles;
    return files;
}

-(NSDictionary *)screenshotsOnDesktop {
    NSDate *lmod = [NSDate dateWithTimeIntervalSinceNow:-5]; // max 5 sec old
    return [self screenshotsAtPath:screenshotLocation modifiedAfterDate:lmod];
}

它们是通知依次调用的前3个方法,而下面的代码是最终方法screenshotsAtPath:modifiedAfterDate:我将警告你非常长,因为它必须确认该文件肯定是截图:< / p>

-(NSDictionary *)screenshotsAtPath:(NSString *)dirpath modifiedAfterDate:(NSDate *)lmod {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *direntries;
    NSMutableDictionary *files = [NSMutableDictionary dictionary];
    NSString *path;
    NSDate *mod;
    NSError *error;
    NSDictionary *attrs;

    dirpath = [dirpath stringByExpandingTildeInPath];

    direntries = [fm contentsOfDirectoryAtPath:dirpath error:&error];
    if (!direntries) {
        return nil;
    }

    for (NSString *fn in direntries) {

        // always skip dotfiles
        if ([fn hasPrefix:@"."]) {
            //[log debug:@"%s skipping: filename begins with a dot", _cmd];
            continue;
        }

        // skip any file not ending in screenshotFilenameSuffix (".png" by default)
        if (([fn length] < 10) ||
            // ".png" suffix is expected
            (![fn compare:screenshotFilenameSuffix options:NSCaseInsensitiveSearch range:NSMakeRange([fn length]-5, 4)] != NSOrderedSame)
            )
        {
            continue;
        }

        // build path
        path = [dirpath stringByAppendingPathComponent:fn];

        // Skip any file which name does not contain a space.
        // You want to avoid matching the filename against
        // all possible screenshot file name schemas (must be hundreds), we make the
        // assumption that all language formats have this in common: it contains at least one space.
        if ([fn rangeOfString:@" "].location == NSNotFound) {
            continue;
        }

        // query file attributes (rich stat)
        attrs = [fm attributesOfItemAtPath:path error:&error];
        if (!attrs) {
            continue;
        }

        // must be a regular file
        if ([attrs objectForKey:NSFileType] != NSFileTypeRegular) {
            continue;
        }

        // check last modified date
        mod = [attrs objectForKey:NSFileModificationDate];
        if (lmod && (!mod || [mod compare:lmod] == NSOrderedAscending)) {
            // file is too old
            continue;
        }

        // find key for NSFileExtendedAttributes
        NSString *xattrsKey = nil;
        for (NSString *k in [attrs keyEnumerator]) {
            if ([k isEqualToString:@"NSFileExtendedAttributes"]) {
                xattrsKey = k;
                break;
            }
        }
        if (!xattrsKey) {
            // no xattrs
            continue;
        }
        NSDictionary *xattrs = [attrs objectForKey:xattrsKey];
        if (!xattrs || ![xattrs objectForKey:@"com.apple.metadata:kMDItemIsScreenCapture"]) {
            continue;
        }

        // ok, let's use this file
        [files setObject:mod forKey:path];
    }

    return files;
}

嗯,你有它。这就是我能够检测用户何时截屏的方式,它可能有一些错误,但目前似乎工作正常。如果您希望这里的所有代码都是pastebin.com上的链接:

标题 - http://pastebin.com/gBAbCBJB

实施 - http://pastebin.com/VjQ6P3zQ

答案 2 :(得分:-3)

当用户进行屏幕截图时,您必须注册一个对象来接收系统通知

这样:

[[NSNotificationCenter defaultCenter] addObserver: theObjectToRecieveTheNotification selector:@selector(theMethodToPerformWhenNotificationIsRecieved) name:@"theNameOftheScreenCapturedNotification" object: optionallyAnObjectOrArgumentThatIsPassedToTheMethodToBecalled];

不确定通知名称是什么,但它可能在那里。

不要忘记在dealloc中取消注册自己:

[[NSNotificationCenter defaultCenter] removeObserver:self];