我一直无法订阅当前窗口的变化,但你可以询问当前应用程序的辅助功能API,以及当前应用程序最前台的窗口。
假设您有一个名为 CurrentAppData 的类,其中包含以下数据:
@interface CurrentAppData : NSObject {
NSString* _title;
AXUIElementRef _systemWide;
AXUIElementRef _app;
AXUIElementRef _window;
}
查找当前应用程序的代码如下所示:
-(void) updateCurrentApplication {
// get the currently active application
_app = (AXUIElementRef)[CurrentAppData
valueOfExistingAttribute:kAXFocusedApplicationAttribute
ofUIElement:_systemWide];
// Get the window that has focus for this application
_window = (AXUIElementRef)[CurrentAppData
valueOfExistingAttribute:kAXFocusedWindowAttribute
ofUIElement:_app];
NSString* appName = [CurrentAppData descriptionOfValue:_window
beingVerbose:TRUE];
[self setTitle:appName];
}
在本例中,_systemWide 变量在类 init 函数中被初始化为: _system = AXUIElementCreateSystemWide();
类函数 valueOfExistingAttribute 如下所示:
// -------------------------------------------------------------------------------
// valueOfExistingAttribute:attribute:element
//
// Given a uiElement and its attribute, return the value of an accessibility
// object's attribute.
// -------------------------------------------------------------------------------
+ (id)valueOfExistingAttribute:(CFStringRef)attribute ofUIElement:(AXUIElementRef)element
{
id result = nil;
NSArray *attrNames;
if (AXUIElementCopyAttributeNames(element, (CFArrayRef *)&attrNames) == kAXErrorSuccess)
{
if ( [attrNames indexOfObject:(NSString *)attribute] != NSNotFound
&&
AXUIElementCopyAttributeValue(element, attribute, (CFTypeRef *)&result) == kAXErrorSuccess
)
{
[result autorelease];
}
[attrNames release];
}
return result;
}
前面的函数取自 Apple UIElementInspector示例,这也是学习 Accessibility API 的一个很好的资源。