Created
August 19, 2025 12:18
-
-
Save T1T4N/a395512b044a16b7acdbe20f353e75aa to your computer and use it in GitHub Desktop.
A short script to center the foremost window on screen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env swift | |
import AppKit | |
// Function to get the frontmost window | |
func getFrontmostWindow() -> AXUIElement? { | |
guard let app = NSWorkspace.shared.frontmostApplication else { | |
return nil | |
} | |
let appElement = AXUIElementCreateApplication(app.processIdentifier) | |
var value: CFTypeRef? | |
let result = AXUIElementCopyAttributeValue(appElement, kAXFocusedWindowAttribute as CFString, &value) | |
return result == .success ? (value as! AXUIElement) : nil | |
} | |
// Function to get the monitor where the window is located | |
func getMonitorForWindow(_ window: AXUIElement) -> NSScreen? { | |
var windowFrame = CGRect.zero | |
var value: CFTypeRef? | |
if AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &value) == .success, | |
AXValueGetValue(value as! AXValue, .cgPoint, &windowFrame.origin) { | |
if AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &value) == .success, | |
AXValueGetValue(value as! AXValue, .cgSize, &windowFrame.size) { | |
return NSScreen.screens.first(where: { $0.frame.intersects(windowFrame) }) | |
} | |
} | |
return nil | |
} | |
// Function to set window position | |
func setWindowPosition(_ window: AXUIElement, position: CGPoint) { | |
var mutablePosition = position | |
if let positionValue = AXValueCreate(AXValueType.cgPoint, &mutablePosition) { | |
AXUIElementSetAttributeValue(window, kAXPositionAttribute as CFString, positionValue) | |
} | |
} | |
// Function to get window size | |
func getWindowSize(_ window: AXUIElement) -> CGSize? { | |
var value: CFTypeRef? | |
if AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &value) == .success { | |
var windowSize = CGSize.zero | |
if AXValueGetValue(value as! AXValue, .cgSize, &windowSize) { | |
return windowSize | |
} | |
} | |
return nil | |
} | |
// Main execution | |
if let window = getFrontmostWindow(), let windowSize = getWindowSize(window) { | |
if let screen = getMonitorForWindow(window) ?? NSScreen.main { | |
let screenFrame = screen.visibleFrame | |
let newX = screenFrame.origin.x + (screenFrame.width - windowSize.width) / 2 | |
let newY = screenFrame.origin.y + (screenFrame.height - windowSize.height) / 2 | |
setWindowPosition(window, position: CGPoint(x: newX, y: newY)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment