2009-01-26 12 views
15

En referencia a un pedido anterior question, me gustaría saber cómo obtener el título del documento activo actual.Obtenga el título de la ventana/documento activa actual en Mac OS X

Probé la mención del guión en las respuestas a la pregunta anterior. Esto funciona, pero solo me da el nombre de la aplicación. Por ejemplo, estoy escribiendo esta pregunta: cuando enciendo el script me da el nombre de la aplicación, es decir, "Firefox". Esto es bastante limpio, pero realmente no ayuda. Prefiero capturar el título de mi documento activo actual. Ver la imagen

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

estoy usando Leopard, por lo que no necesitaba compatibilidad con versiones anteriores. También estoy usando el Appkit de Python para obtener acceso a la clase NSWorkspace, pero si me dices el código Objective-C, podría averiguar la traducción a Python.


Ok, tengo una solución que no es muy satisfactoria, por eso no marcó la respuesta de Koen Bok. Al menos no todavía.

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 

Guárdelo como script e inícielo con osascript desde el shell.

+0

Gracias por la solución applescript. ¿Alguna vez has encontrado la manera de hacerlo a través de Python? – Amjith

Respuesta

2

En Objective-C, la respuesta corta, con un poco de cacao y sobre todo la Carbon Accessibility API es:

// 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); 

Alternativamente, puede ser más fácil de usar la API CGWindow, como se alude en this StackOverflow answer.