简体   繁体   中英

Macos Screen capture with LaunchAgent

I made a screen capture command line tool LaunchAgent. When launched, the screen capture policy alert did not pop up, so I couldn't capture the right screenshots. I have no idea how to correct this. Could you help me with it? Thank you.

the command line tool path: /bin/capture

code follows:

#import <Foundation/Foundation.h>

#import <Cocoa/Cocoa.h>



int main(int argc, const char * argv[]) {

    @autoreleasepool {

        // insert code here...

        NSLog(@"capture screen...");

        CGRect mainRect = CGDisplayBounds(CGMainDisplayID());

        CGImageRef desktopImage = CGWindowListCreateImage(mainRect, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageBestResolution | kCGWindowImageShouldBeOpaque);

        NSBitmapImageRep *bmpImgRef = [[NSBitmapImageRep alloc] initWithCGImage:desktopImage];

        NSData *data = [bmpImgRef representationUsingType:NSBitmapImageFileTypeJPEG properties:@{NSImageCompressionFactor: @(1)}];

        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];

        [fmt setDateFormat:@"yyyyMMdd_hh:mm:ss"];

        [data writeToURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"/tmp/%@.jpg", [fmt stringFromDate:[NSDate date]]]] atomically:true];

    }

    return 0;

}

the LaunchAgent plist file path: /Library/LaunchAgent/com.test.launchagent.screencapture.plist

and the LaunchAgent plist follows:

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">

<plist version="1.0">

<dict>

    <key>Label</key>

    <string>com.test.launchagent.screencapture</string>

    <key>ProgramArguments</key>

    <array>

        <string>/bin/capture</string>

    </array>

    <key>RunAtLoad</key>

    <true/>

</dict>

</plist>

You do need several things to get this work.

First of all, you need to have an Info.plist for your binary. You can use embedded Info.plist (can be set in Xcode build settings) if you care about keeping it just single unix file, not creating a bundle.

Second, you have to change launch plist to run your program in Aqua session.

With such steps you should be able to run this and see policy popup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM