Does anyone has any idea how can I capture screen using objective c in mac os?
to be more specific, how can I capture the active / focused application screen then create an image into a specified path.
Any help is highly appreciated.
Asked
Active
Viewed 7,481 times
8
3 Answers
10
@Daniel, You don't need to understand and implement the whole "Son of Grab". You just need the code below.
The following function will give you the screenshot
// This just invokes the API as you would if you wanted to grab a screen shot. The equivalent using the UI would be to
// enable all windows, turn off "Fit Image Tightly", and then select all windows in the list.
CGImageRef screenShot = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
Use the following code to convert it to a NSImage
NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:screenShot];
// Create an NSImage and add the bitmap rep to it...
NSImage *image = [[NSImage alloc] init];
[image addRepresentation:bitmapRep];
[bitmapRep release];
bitmapRep = nil;

Linus Unnebäck
- 23,234
- 15
- 74
- 89

ThE uSeFuL
- 1,456
- 1
- 16
- 29
-
2Remember to call `CFRelease(screenShot);` as well so that you don't leak it. – Aaron May 24 '18 at 23:39
-
Learnt in a hard way @Aaron – Tamal Sen Sep 24 '20 at 11:43
4
Have you checked out Apple's “Son of Grab” for capturing images of windows with the CGWindow api?

Motti Shneor
- 2,095
- 1
- 18
- 24

Arkku
- 41,011
- 10
- 62
- 84
-
1yeah, i have seen it, i'm rather new to objective c, Son of Grab is a bit difficult for me. my requirement is very simple, create an app which runs in background, upon meeting certain criteria, just capture the current focused window and create an image on a specified path – Daniel Nov 07 '09 at 05:48
-
Hi, the link to "Son of Grab" is dead... would you care to tell where to find it? – Motti Shneor Nov 02 '21 at 08:23
-
@MottiShneor It is archived https://developer.apple.com/library/archive/samplecode/SonOfGrab/Introduction/Intro.html#//apple_ref/doc/uid/DTS10004490 – Arkku Nov 02 '21 at 09:20
-
Hi, is there a way to capture screen shots continuously with higher fps? – Ananth Kamath May 18 '22 at 07:57