简体   繁体   English

使用 LaunchAgent 的 Macos 屏幕截图

[英]Macos Screen capture with LaunchAgent

I made a screen capture command line tool LaunchAgent.我做了一个截屏命令行工具 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命令行工具路径: /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 LaunchAgent plist 文件路径: /Library/LaunchAgent/com.test.launchagent.screencapture.plist

and the LaunchAgent plist follows: LaunchAgent plist 如下:

<!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.首先,您需要为您的二进制文件提供一个 Info.plist。 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.如果您关心仅保留单个 unix 文件而不是创建捆绑包,则可以使用嵌入式 Info.plist(可以在 Xcode 构建设置中设置)。

Second, you have to change launch plist to run your program in Aqua session.其次,您必须更改启动 plist 以在Aqua session 中运行您的程序。

With such steps you should be able to run this and see policy popup.通过这些步骤,您应该能够运行它并查看策略弹出窗口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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