Skip to content

Instantly share code, notes, and snippets.

@foxt
Last active July 27, 2023 21:58
Show Gist options
  • Save foxt/95304061c8ee0d4a43305e3dfb28f313 to your computer and use it in GitHub Desktop.
Save foxt/95304061c8ee0d4a43305e3dfb28f313 to your computer and use it in GitHub Desktop.
Xamarin/.NET 7/Microsoft.macOS - Create a screenshot of all windows open.
// Captures a screenshot of all windows open and saves it to pages in a PDF file.
[DllImport("/System/Library/Frameworks/QuartzCore.framework/QuartzCore")]
static extern IntPtr CGWindowListCopyWindowInfo(CGWindowListOption option, uint relativeToWindow);
IntPtr windowsPtr = CGWindowListCopyWindowInfo(CGWindowListOption.All, 0);
var windows = (NSArray)Runtime.GetNSObject(windowsPtr)!;
var images = new List<CGImage>();
foreach (var window in windows) {
var windowNumber = (NSNumber)window.P("kCGWindowNumber");
Console.WriteLine(window);
var image = CGImage.ScreenImage(windowNumber.Int32Value, CGRect.Null, CGWindowListOption.IncludingWindow, CGWindowImageOption.BestResolution);
if (image == null)
continue;
images.Add(image);
}
var url = new NSUrl("file:///Users/foxt/testimages/test.pdf");
var dest = CGImageDestination.Create(url, "com.adobe.pdf", images.Count);
foreach (CGImage image in images)
dest.AddImage(image);
dest.Close();
// Helper class to add a NSObject.P(string property) rather than having to NSObject.ValueForKey(new NSString(string property))
public static class NSObjectExtensions {
public static NSObject P(this NSObject obj,string propertyName) =>
obj.ValueForKey(new NSString(propertyName));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment