开发者

Accessibility API - Cocoa

开发者 https://www.devze.com 2023-02-12 06:08 出处:网络
Is there any way (I think using the 开发者_开发问答Accessibility API) to be able to press a button/keystroke in my app and then hover over a menubar item and press again and then return the name of th

Is there any way (I think using the 开发者_开发问答Accessibility API) to be able to press a button/keystroke in my app and then hover over a menubar item and press again and then return the name of the menu item, the menu it's in and the app?

I want to do this in Cocoa/Objective-C (Mac).


That's what the kAXMenuItemSelectedNotification notification is for. An easy way to play with this stuff is using UI Browser:

  • Pick an application in the "Target" popup menu.
  • Pick "Notifications" from the "Drawer" popup menu.
  • Click "menu item selected" and "Register" (or just double-click in the table).
  • Choose "Notification Log" from the View menu.
  • Switch to the application you chose and pick a menu item.

That lets you see when notifications are triggered. Your code could look something like this:

AXError err;
AXObserverRef observer;

pid_t currentAppPID = [NSRunningApplication currentApplication].processIdentifier;
if ( (err = AXObserverCreate(currentAppPID, notificationCallback, &observer) != kAXErrorSuccess); // XXX failed

CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(observer), kCFRunLoopDefaultMode);

AXUIElementRef element = AXUIElementCreateApplication(currentAppPID);
if (element == NULL); // XXX failed
if ( (err = AXObserverAddNotification(observer, element, kAXMenuItemSelectedNotification, NULL)) != kAXErrorSuccess); // XXX failed

Note that you'll have to observe every running app individually (and additional apps as they launch/quit), or register for NSWorkspaceDidActivateApplicationNotification and deregister/register with the frontmost app at that point (the latter is probably easiest under 10.6 because you get a NSRunningApplication as part of the notification).

I would think actually selecting the item would be easier for a user, but if you really do want to press another key to complete the action, you can observe kAXSelectedChildrenChanged, which will be triggered when the selection moves from one menu item to another.

0

精彩评论

暂无评论...
验证码 换一张
取 消