Last active
July 27, 2023 21:58
-
-
Save foxt/95304061c8ee0d4a43305e3dfb28f313 to your computer and use it in GitHub Desktop.
Xamarin/.NET 7/Microsoft.macOS - Create a screenshot of all windows open.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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