Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take screenshots of specific application window on Mac

I'm trying to make a screen cast application which casts individual application windows instead of the whole screen. To start with I'm trying to take simple screenshots of individual applications on my mac using Xcode.

So far, I'm trying to make use of CGWindowListCreateImage but I'm running into problems.

EDIT So here's a small example of how I managed to get the WindowID. It's pretty simple afterwards to take a screenshot using it. First you add a global monitor for events, more specifically NSMouseEvents. I used mouse down. The window information is stored in the mouse event.

    CGWindowID windowID = (CGWindowID)[event windowNumber];

You can then take a screenshot of JUST the app, without shadows etc using the code below.

CGImageRef image = CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, self.WindowID, kCGWindowImageBoundsIgnoreFraming);

Let me know if you need more.

like image 232
user3339357 Avatar asked Dec 19 '22 17:12

user3339357


2 Answers

So here's a small example of how I managed to get the WindowID. It's pretty simple afterwards to take a screenshot using it. First you add a global monitor for events, more specifically NSMouseEvents. I used mouse down. The window information is stored in the mouse event.

CGWindowID windowID = (CGWindowID)[event windowNumber];

You can then take a screenshot of JUST the app, without shadows etc using the code below.

CGImageRef image = CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, self.WindowID, kCGWindowImageBoundsIgnoreFraming);

Let me know if you need more.

like image 118
user3339357 Avatar answered Jan 17 '23 18:01

user3339357


Based on user3339357 's answer, in Swift 3

let gImage = CGWindowListCreateImage(
      CGRect.null,
      CGWindowListOption.optionIncludingWindow,
      CGWindowID(window.windowNumber),
      CGWindowImageOption.bestResolution)

let image = NSImage(cgImage: cgImage!, size: window.frame.size)
like image 28
onmyway133 Avatar answered Jan 17 '23 17:01

onmyway133