获取Mac OS X中当前活动窗口/文档的标题

2024-06-14 06:09:43 发布

您现在位置:Python中文网/ 问答频道 /正文

参考之前询问的question,我想知道如何获取当前活动文档的标题。

我试过在回答上述问题时提到的剧本。这是可行的,但只提供了应用程序的名称。例如,我在写这个问题:当我启动脚本时,它会给我应用程序的名称,即“Firefox”。这是相当整洁,但没有真正的帮助。我希望捕获当前活动文档的标题。看图片。

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

我使用的是Leopard,所以不需要向后兼容。另外,我使用Python的Appkit来访问NSWorkspace类,但是如果您告诉我Objective-C代码,我可以找到Python的转换。


好吧,我有一个不太令人满意的解决方案,这就是为什么我没有马克·科恩·博克的答案。至少现在还没有。
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调用它。


Tags: oftoname文档脚本名称应用程序标题
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);

或者,如this StackOverflow answer中所述,使用CGWindow API可能更简单。

据我所知,你最好的办法是包装一个AppleScript。但AppleScript对我来说很神奇,所以我把它留给提问者练习:-)

这可能有点帮助:A script to resize frontmost two windows to fill screen - Mac OS X Hints

相关问题 更多 >