2009-01-26 183 views
15

參考先前詢問的question,我想知道如何獲取當前活動文檔的標題。在Mac OS X中獲取當前活動窗口/文檔的標題

我在上面的問題的答案中嘗試了腳本提及。這工作,但只給我的應用程序的名稱。例如,我正在寫這個問題:當我啓動腳本時,它給了我應用程序的名稱,即「Firefox」。這非常整潔,但並沒有真正的幫助。我寧願捕捉當前活動文檔的標題。看到圖片。

Firefox title http://img.skitch.com/20090126-nq2egknhjr928d1s74i9xixckf.jpg

我使用的豹,所以沒有向後兼容性需要。此外,我正在使用Python的Appkit獲得對NSWorkspace類的訪問權限,但如果您告訴我Objective-C代碼,則可以找出Python的翻譯。


好吧,我有一個解決方案不是很滿意,這就是爲什麼我不標記Koen Bok的答案。至少還沒有。

tell application "System Events" 
set frontApp to name of first application process whose frontmost is true 
end tell 
tell application frontApp 
if the (count of windows) is not 0 then 
    set window_name to name of front window 
end if 
end tell 

另存爲腳本並使用shell中的osascript調用它。

+0

謝謝你的applescript解決方案。你有沒有找到一種方法通過python來做到這一點? – Amjith 2012-02-12 20:25:22

回答

2

在Objective-C,簡單的答案,用少量可可和大多Carbon Accessibility API是:

// Get the process ID of the frontmost application. 
NSRunningApplication* app = [[NSWorkspace sharedWorkspace] 
           frontmostApplication]; 
pid_t pid = [app processIdentifier]; 

// See if we have accessibility permissions, and if not, prompt the user to 
// visit System Preferences. 
NSDictionary *options = @{(id)kAXTrustedCheckOptionPrompt: @YES}; 
Boolean appHasPermission = AXIsProcessTrustedWithOptions(
          (__bridge CFDictionaryRef)options); 
if (!appHasPermission) { 
    return; // we don't have accessibility permissions 

// Get the accessibility element corresponding to the frontmost application. 
AXUIElementRef appElem = AXUIElementCreateApplication(pid); 
if (!appElem) { 
    return; 
} 

// Get the accessibility element corresponding to the frontmost window 
// of the frontmost application. 
AXUIElementRef window = NULL; 
if (AXUIElementCopyAttributeValue(appElem, 
     kAXFocusedWindowAttribute, (CFTypeRef*)&window) != kAXErrorSuccess) { 
    CFRelease(appElem); 
    return; 
} 

// Finally, get the title of the frontmost window. 
CFStringRef title = NULL; 
AXError result = AXUIElementCopyAttributeValue(window, kAXTitleAttribute, 
        (CFTypeRef*)&title); 

// At this point, we don't need window and appElem anymore. 
CFRelease(window); 
CFRelease(appElem); 

if (result != kAXErrorSuccess) { 
    // Failed to get the window title. 
    return; 
} 

// Success! Now, do something with the title, e.g. copy it somewhere. 

// Once we're done with the title, release it. 
CFRelease(title); 

可替代地,它可以是簡單的使用CGWindow API,如在this StackOverflow answer提到。

相關問題