Mac OSX:如何检测未选择任何窗口?

3

我正在开发一个可以调整选定窗口大小的应用程序。当任何窗口被选中时,它可以成功地工作。但是当没有窗口被选中时,它会崩溃。

目前从以下代码中获取最前面的窗口。

AXUIElementCopyAttributeValue(frontMostApp, kAXFocusedWindowAttribute, (CFTypeRef *)&frontMostWindow);

但是如何检测控件在桌面上还是所有窗口都不活动。

2个回答

4

AXUIElementCopyAttributeValue() 返回 AXError,因此您可以捕获它,然后 检查发生了什么

AXError error = AXUIElementCopyAttributeValue(frontMostApp, kAXFocusedWindowAttribute, (CFTypeRef *)&frontMostWindow);
if (error != kAXErrorSuccess) {
    //solve problems here
}

在您的具体情况下,返回了一个错误值:kAXErrorNoValue = -25212

这似乎是有效的。感谢 @eligat。希望它将来不会出现任何错误。 - Piyush Mathur

1
你可以使用AppleScript来完成这个任务。在Xcode中创建新项目时,你可以选择“Cocoa-AppleScript”作为应用程序类型,在OS X > 其他下进行选择,以创建一个同时具有Obj-C和AppleScript的应用程序。你可以使用以下代码使具有焦点的应用程序执行某些操作:
tell current app to ...

您可以使用此代码来更改窗口的大小。
set the bounds of the front window to {x, y, x + width, y + height}

这里的xy是距离左上角的距离。
您可以将此添加到您的项目中并修改当前位于最前面的窗口的大小。这意味着具有焦点的应用程序的最前面的窗口将被调整大小。这是一个工作且完全交互式的示例:
set theWindows to the windows of the current application
if the length of theWindows is 0 then
    display alert "There are no windows to resize"
else
    display dialog "Enter x" default answer ""
    set x to text returned of result as number
    display dialog "Enter y" default answer ""
    set y to text returned of result as number
    display dialog "Enter width" default answer ""
    set width to text returned of result as number
    set width to (x + width)
    display dialog "Enter height" default answer ""
    set height to text returned of result as number
    set height to (y + height)
    tell current application to set the bounds of the front window to {x, y, width, height}
end if

在Yosemite中,您可以使用“Script Editor”应用程序创建没有任何核心内容的应用程序,只需使用AppleScript即可。在Mavericks和旧系统中,该应用程序称为“AppleScript Editor”。如果您需要Objective-C用于应用程序的其他部分,则可以使用我之前描述的方法创建Cocoa-AppleScript程序。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接