You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将我的应用窗口居中显示在另一应用的窗口中?

实现方案说明

可行性结论

可行,但需严格遵守App Store审核规则,仅使用公开API实现。

具体实现步骤

1. 借助Accessibility框架获取前端窗口框架

NSWorkspace.shared.frontmostApplication仅能获取应用实例,无法直接拿到窗口位置信息,需通过Accessibility框架的公开接口实现:

  • 导入Accessibility框架
  • 获取前端应用的PID:NSWorkspace.shared.frontmostApplication?.processIdentifier
  • 通过PID创建AXUIElement实例,以此为入口获取应用的窗口列表
  • 筛选出当前聚焦的窗口,再获取其AXFrame属性得到窗口框架

2. 关键代码示例

import Cocoa
import Accessibility

func getFrontmostWindowFrame() -> CGRect? {
    guard let frontApp = NSWorkspace.shared.frontmostApplication,
          let pid = frontApp.processIdentifier else { return nil }
    
    let appElement = AXUIElementCreateApplication(pid)
    var windows: AnyObject?
    let status = AXUIElementCopyAttributeValue(appElement, kAXWindowsAttribute as CFString, &windows)
    
    guard status == .success, let windowList = windows as? [AXUIElement] else { return nil }
    
    // 遍历窗口列表,找到当前聚焦的窗口
    for window in windowList {
        var isFocused: AnyObject?
        if AXUIElementCopyAttributeValue(window, kAXFocusedAttribute as CFString, &isFocused) == .success,
           let focused = isFocused as? Bool, focused {
            var frame: AnyObject?
            if AXUIElementCopyAttributeValue(window, kAXFrameAttribute as CFString, &frame) == .success,
               let frameRect = frame as? CGRect {
                return frameRect
            }
        }
    }
    
    return nil
}

// 将自身窗口居中到前端窗口
if let frontFrame = getFrontmostWindowFrame(),
   let myWindow = NSApplication.shared.windows.first {
    let centerX = frontFrame.midX - myWindow.frame.width / 2
    let centerY = frontFrame.midY - myWindow.frame.height / 2
    myWindow.setFrameOrigin(NSPoint(x: centerX, y: centerY))
    myWindow.makeKeyAndOrderFront(nil)
}

3. App Store审核注意事项

  • 必须在Info.plist中添加NSAccessibilityUsageDescription,明确说明应用需要辅助功能权限的原因,否则会被审核拒绝
  • 禁止使用任何私有API,所有操作必须基于公开的Accessibility接口
  • 测试时需确保用户已在系统偏好设置>安全性与隐私>隐私>辅助功能中授权你的应用

内容的提问来源于stack exchange,提问作者Wojciech Kulik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 02:01:11