Skip to content

Instantly share code, notes, and snippets.

@developer-commit
Created January 25, 2025 07:32
Show Gist options
  • Save developer-commit/7cb1d404783431c17e3d347adf9c0745 to your computer and use it in GitHub Desktop.
Save developer-commit/7cb1d404783431c17e3d347adf9c0745 to your computer and use it in GitHub Desktop.
example by window capture
// origanl code : https://stackoverflow.com/questions/78846311/screencapturekit-example-in-go-c
import Foundation
import ScreenCaptureKit
import CoreGraphics
import AppKit
func captureScreenshot(display: SCDisplay?, window: SCWindow, app: SCRunningApplication,completion: @escaping (NSImage?) -> Void) {
let filter: SCContentFilter
if let display = display {
filter = SCContentFilter(display: display, including: [app], exceptingWindows: [])
} else {
filter = SCContentFilter()
}
let configuration = SCStreamConfiguration()
configuration.showsCursor = true
configuration.scalesToFit = false
SCScreenshotManager.captureImage(contentFilter: filter, configuration: configuration) { image, error in
if let error = error {
print("Error capturing screenshot: \(error.localizedDescription)")
completion(nil)
} else if let image = image {
let cropRect = CGRect(x: window.frame.origin.x, y: window.frame.origin.y, width: window.frame.width, height: window.frame.height)
guard let croppedCGImage = image.cropping(to: cropRect) else { return}
completion(NSImage(cgImage: croppedCGImage, size: NSSize( width: window.frame.width, height: window.frame.height)))
//completion(NSImage(cgImage: image, size: NSSize(width: image.width, height: image.height)))
} else {
print("No image captured")
completion(nil)
}
}
}
// Main execution
func main() {
let semaphore = DispatchSemaphore(value: 0)
Task {
do {
let content = try await SCShareableContent.current
guard let runapp = content.applications.first(where: { $0.applicationName == "Safari" }) else {
print("\nSafari is not running.")
return
}
guard let app_window = content.windows.first(where: {
$0.owningApplication == runapp &&
$0.title != nil &&
!$0.title!.isEmpty
}) else {
return
}
guard !content.displays.isEmpty else {
print("No displays found")
semaphore.signal()
return
}
print("Available displays:")
for (index, display) in content.displays.enumerated() {
print("\(index + 1). \(display.displayID) - \(display.width)x\(display.height)")
}
print("Enter the number of the display to capture (or press Enter for main display):")
let input = readLine()?.trimmingCharacters(in: .whitespacesAndNewlines)
let selectedDisplay: SCDisplay?
if let index = Int(input ?? ""), (1...content.displays.count).contains(index) {
selectedDisplay = content.displays[index - 1]
} else {
selectedDisplay = content.displays.first
}
captureScreenshot(display: selectedDisplay, window: app_window, app: runapp) { image in
if let image = image {
let currentDirectoryURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
let fileURL = currentDirectoryURL.appendingPathComponent("screenshot.png")
if let tiffData = image.tiffRepresentation,
let bitmapImage = NSBitmapImageRep(data: tiffData),
let pngData = bitmapImage.representation(using: .png, properties: [:]) {
do {
try pngData.write(to: fileURL)
print("Screenshot saved to: \(fileURL.path)")
} catch {
print("Error saving screenshot: \(error.localizedDescription)")
}
} else {
print("Error converting image to PNG data")
}
} else {
print("Failed to capture screenshot")
}
semaphore.signal()
}
} catch {
print("Error getting shareable content: \(error.localizedDescription)")
semaphore.signal()
}
}
semaphore.wait()
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment