Search code examples
objective-cmacoscocoascreenshot

Taking screenshot programmatically in mac only for application window


I have to add the ability to take screenshots to my OSX apps, but the Apple demo is only giving me the whole screen image, I just want to only my application window image.

My code is:

NSInteger displaysIndex = 0;
if(displays != nil)
{
    free(displays);
}


CGError             err = CGDisplayNoErr;
CGDisplayCount      dspCount = 0;

/* How many active displays do we have? */
err = CGGetActiveDisplayList(0, NULL, &dspCount);

/* If we are getting an error here then their won't be much to display. */
if(err != CGDisplayNoErr)
{
    return;
}
/* Allocate enough memory to hold all the display IDs we have. */
displays = calloc((size_t)dspCount, sizeof(CGDirectDisplayID));

// Get the list of active displays
err = CGGetActiveDisplayList(dspCount,
                             displays,
                             &dspCount);

/* Make a snapshot image of the current display. */
CGImageRef image = CGDisplayCreateImage(displays[displaysIndex]);

What should I change in code so I will get only my app's window?


Solution

  • Simple.

    NSImage *captureImage  = [[NSImage alloc] initWithData:[self.view dataWithPDFInsideRect:[self.view bounds]]];
    

    please check and let me know. This is captured current active window.