Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@coreh
Last active April 20, 2023 16:37
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreh/6349074 to your computer and use it in GitHub Desktop.
Save coreh/6349074 to your computer and use it in GitHub Desktop.
Screen capture in Cocoa (Grabs the screen contents and puts it into a NSImage)
NSImage *CaptureScreen() {
// Get the Screen Rect
NSRect screenRect = [[NSScreen mainScreen] frame];
// Create a CGImage with the screen contents
CGImageRef cgImage = CGWindowListCreateImage(screenRect, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
// Convert the CGImage into a NSBitmapImageRep
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
// Release the CGImage
CGImageRelease(cgImage);
// Create a NSImage
NSImage *image = [[NSImage alloc] init];
// Add the NSBitmapImageRep
[image addRepresentation:rep];
return image;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment