How to get windows list from core-grapics API with fast

I am trying to get a list of windows on OSX from the Core Graphics APIs using Swift (to then simulate their image). After some research, I found the CGWindowListCopyWindowInfo Objective-C API call with the following signature:

CFArrayRef CGWindowListCopyWindowInfo(
   CGWindowListOption option,
   CGWindowID relativeToWindow
);

Parameters

: options describing which window dictionaries to return. Typical options allow you to return dictionaries for all windows or for windows above or below the window specified in relativeToWindow. For more information, see the list of Option Constants windows.

relativeToWindow: window identifier to use as a reference point in determining which other window dictionaries to return. For those that do not require a reference window, the parameter may be kCGNullWindowID.

https://developer.apple.com/library/mac/documentation/Carbon/Reference/CGWindow_Reference/Reference/Functions.html

In my quick application, I tried using it as follows:

import Cocoa
import CoreFoundation

let option: CGWindowListOption = kCGWindowListOptionOnScreenOnly
let relativeToWindow: CGWindowID = kCGNullWindowID

let info = CGWindowListCopyWindowInfo(option, relativeToWindow)

But Xcode (playground) tells me

  • it cannot use int like CGWindowListOption (kCGWindowListOptionOnScreenOnly == 0)
  • kCGNullWindowID is an unresolved identifier

What am I doing wrong here?

+4
source share
1 answer
  • kCGWindowListOptionOnScreenOnlyis Int, you need to convert that to CGWindowListOptionaka UInt32.
  • Definition C

    #define kCGNullWindowID ((CGWindowID)0) 
    

    not imported into Swift, so you should use a constant 0.

  • , CGWindowListCopyWindowInfo() Unmanaged<CFArray>!, takeRetainedValue() ( " Cocoa " ).

:

let option = CGWindowListOption(kCGWindowListOptionOnScreenOnly)
let relativeToWindow = CGWindowID(0)
let info = CGWindowListCopyWindowInfo(option, relativeToWindow).takeRetainedValue()

for dict in info as! [ [ String : AnyObject] ] {
    // ...
}

Swift 3:

if let info = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[ String : Any]] {
    for dict in info {
        // ...
    }
}
+9

Source: https://habr.com/ru/post/1588888/


All Articles