在swift中设置屏幕上所有窗口的大小和位置

时间:2017-11-24 22:44:50

标签: swift macos cocoa

是否可以在swift中获取所有应用程序的列表,其中包含前景窗口,然后设置这些窗口的大小和位置。

我得到像这样的Windows属性列表

let type = CGWindowListOption.optionOnScreenOnly
let windowList = CGWindowListCopyWindowInfo(type, kCGNullWindowID) as NSArray? as? [[String: AnyObject]]

for entry  in windowList!
{

  var owner = entry[kCGWindowOwnerName as String] as! String
  var bounds = entry[kCGWindowBounds as String] as? [String: Int]
  var pid = entry[kCGWindowOwnerPID as String] as? Int32

  print ("\(owner)  \(bounds) \(pid)  ")

  if owner == "Erinnerungen"
  { bounds!["X"] = 0
    bounds!["Y"] = 0
    print("reset bounds")

    let appRef = AXUIElementCreateApplication(pid!);  //TopLevel Accessability Object of PID
    print(appRef)

    var value: AnyObject?
    let result = AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute as CFString, &value)

    if result == .success, let windowList = value as? [AXUIElement]
    { // DO ANYTHING          
    } else
    { print("Result no Success or no valid windowlist returnd")          
    }
  }
}

现在我尝试改变一些原因,但这没有效果。 同时尝试获取PID的TopLevel可访问性对象的AttributeValue返回AXError(kAXErrorCannotComplete = -25204)

1 个答案:

答案 0 :(得分:3)

得益于@Martin R的帮助

let type = CGWindowListOption.optionOnScreenOnly
let windowList = CGWindowListCopyWindowInfo(type, kCGNullWindowID) as NSArray? as? [[String: AnyObject]]

for entry  in windowList!
{
  let owner = entry[kCGWindowOwnerName as String] as! String
  var bounds = entry[kCGWindowBounds as String] as? [String: Int]
  let pid = entry[kCGWindowOwnerPID as String] as? Int32

  if owner == "Terminal"
  {
    let appRef = AXUIElementCreateApplication(pid!);  //TopLevel Accessability Object of PID

    var value: AnyObject?
    let result = AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute as CFString, &value)

    if let windowList = value as? [AXUIElement]
    { print ("windowList #\(windowList)")
      if let window = windowList.first 
      {            
        var position : CFTypeRef
        var size : CFTypeRef
        var  newPoint = CGPoint(x: 0, y: 0)
        var newSize = CGSize(width: 800, height: 800)

        position = AXValueCreate(AXValueType(rawValue: kAXValueCGPointType)!,&newPoint)!;
        AXUIElementSetAttributeValue(windowList.first!, kAXPositionAttribute as CFString, position);

        size = AXValueCreate(AXValueType(rawValue: kAXValueCGSizeType)!,&newSize)!;
        AXUIElementSetAttributeValue(windowList.first!, kAXSizeAttribute as CFString, size);
      }
    } 
  }
}