سؤال

I already wrote a code which sets me able to get the selected text in TextEdit.app or other few apps. My problem is I need to get the selected text in any app. It seems the accessibility API is not capable to get the selected text of every app as I can evidence by using the Accessibility Inspector.

This first image shows how the accessibility API can get the selected text as an attribute from the AXTextArea in the TextEdit.app:

The Accessibility Inspector detecting AXTextArea and AXSelectedText in the Text Edit App

Then I try to get the same information from TextWrangler.app but it won't work the same way.

The Accessibility Inspector can't detect selected text in the Text Wrangler App

Is there an alternative to get the selected text information from any app or at least most of them?

هل كانت مفيدة؟

المحلول

The only alternative I know is to send a Cmd-c and monitor the pasteboard:

+ (void)sendCommandC
{
    CGKeyCode _C = [[DJRKeyboardTools sharedInstance] keyCodeForChar:'c'];
    CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
    CGEventRef pasteCommandDown = CGEventCreateKeyboardEvent(source, _C, YES);
    CGEventSetFlags(pasteCommandDown, kCGEventFlagMaskCommand);
    CGEventRef pasteCommandUp = CGEventCreateKeyboardEvent(source, _C, NO);

    CGEventPost(kCGAnnotatedSessionEventTap, pasteCommandDown);
    CGEventPost(kCGAnnotatedSessionEventTap, pasteCommandUp);

    CFRelease(pasteCommandUp);
    CFRelease(pasteCommandDown);
    CFRelease(source);    
}

That piece of code will post the keyboard event. You'll need a bit more code. These gists of mine can help you to start:

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top