Skip to content

Instantly share code, notes, and snippets.

@nl5887
Created September 2, 2014 07:13
Show Gist options
  • Save nl5887/9eaad4faac9bf8852092 to your computer and use it in GitHub Desktop.
Save nl5887/9eaad4faac9bf8852092 to your computer and use it in GitHub Desktop.
Creating an animated gif of currently active window in Core Foundation (OSX).
long windowId = kCGNullWindowID;
CGRect *temp = new CGRect;
// get all windows on the current screen
CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionAll | kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
// find the current window, that will be the first one on layer 0
CFIndex windowNum = CFArrayGetCount(windowList);
for (int i=0;i<(int)windowNum;i++) {
CFDictionaryRef info = (CFDictionaryRef)CFArrayGetValueAtIndex(windowList, i);
CFNumberRef currentWindowLayer = (CFNumberRef)CFDictionaryGetValue(info, kCGWindowLayer);
long layer = LONG_MAX;
CFNumberGetValue(currentWindowLayer, kCFNumberLongType, &layer);
if (layer > 0)
continue;
// get window title (not necessary, but as reference, don't forget to free the string)
CFStringRef currentTitle = (CFStringRef)CFDictionaryGetValue(info, kCGWindowName);
char* bla = MYCFStringCopyUTF8String(currentTitle);
// get the window number
CFNumberRef currentWindowNumber = (CFNumberRef)CFDictionaryGetValue(info, kCGWindowNumber);
CFNumberGetValue(currentWindowNumber, kCFNumberLongType, &windowId);
// get the window rect
CFDictionaryRef bounds = (CFDictionaryRef)CFDictionaryGetValue(info, kCGWindowBounds);
CGRectMakeWithDictionaryRepresentation(bounds, temp);
// break on the first window, that will be the current
break;
}
CFStringRef filename = CFSTR("/tmp/test.gif");
CFURLRef urlRef = CFURLCreateWithFileSystemPath( kCFAllocatorDefault, filename, kCFURLPOSIXPathStyle, false );
// create new destination, for an animated gif, change the count variable
int count = 1;
CGImageDestinationRef idst = CGImageDestinationCreateWithURL( urlRef, kUTTypeGIF, count, NULL );
// set the delay in case of animated gif
float delay = 1.0 / (1e6/1e2);
CFNumberRef delayNumber = CFNumberCreate(NULL, kCFNumberFloatType, &delay);
const void *keys[1] = { kCGImagePropertyGIFDelayTime };
const void *values[1] = { delayNumber };
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 3,
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
// create the screenshot of windowId with rect temp
CGImageRef screenShot = CGWindowListCreateImage(*temp, kCGWindowListOptionIncludingWindow, windowId, kCGWindowImageDefault);
// add screenshot to the destination
CGImageDestinationAddImage( idst, screenShot, options );
// release screenshot
CGImageRelease(screenShot);
// finalize the animated gif
CGImageDestinationFinalize( idst );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment