For macOS Cocoa, how do I specify a window or a rectangle on the screen for taking a screenshot?

ε祈祈猫儿з 提交于 2021-02-11 14:10:45

问题


I have written a macOS app for measuring image files, and I wish to add a feature for capturing screenshots. I wish for it to have a user interface for doing it much like what the macOS app "Preview" has.

To use its screenshot function, one does File > Take Screenshot, and one gets a submenu with these options:

  • From Selection...
  • From Window...
  • From Entire Screen

"From Selection..." lets you select a rectangle on the screen by clicking and dragging.

"From Window..." lets you select an app window.

"From Entire Screen" is what it says.

I can find the code for getting the screenshot as an image object, but I haven't been able to find any code for the user-interface part, the part for selecting a rectangle or a window. Does anyone know how to do that? Or else have some code for doing that.


回答1:


The following code should give you a window shot:

@objc func myBtnAction(_ sender:AnyObject ) {
 let windowID : Int = window!.windowNumber
 let windowImage: CGImage? = CGWindowListCreateImage(.null, .optionIncludingWindow, CGWindowID(windowID), [.nominalResolution])
 let bitmapRep = NSBitmapImageRep(cgImage: windowImage!)
 let image = NSImage()
 image.addRepresentation(bitmapRep)
 let pngData = bitmapRep.representation(using: .png, properties:[:])
 // your fileURL here
 let fileURL = URL(fileURLWithPath: "/Users/xxxx/Desktop/WndShot.png")
 do {
   try pngData!.write(to: fileURL)
   print("File saved: \(fileURL.absoluteURL)")
   } catch {
   print(error.localizedDescription)
  }
}

I turned off the SandBox.




回答2:


Try invoking the screencapture command-line tool:

screencapture -i -c

This will run the default macOS interface for selecting a region on the screen and store the captured image on the clipboard. Use the -Jwindow to capture a window instead:

screencapture -i -c -Jwindow

Or replace the -i flag with the -S flag to capture the entire screen non-interactively:

screencapture -S -c -Jwindow


来源:https://stackoverflow.com/questions/61731812/for-macos-cocoa-how-do-i-specify-a-window-or-a-rectangle-on-the-screen-for-taki

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!