Friday, May 6, 2011

Cocoa: What NSTextView the insertion point is currently blinking in?

Hi!

Given an NSApp object (aka [NSApplication sharedApplication]), how can I get the currently active NSTextView, where the insertion point is blinking right now (if there is one)? :-)

I can go [[NSApp keyWindow] contentView] and try traversing the whole view hierarchy, but that seems too hard. Ideal code would be: [NSApp focusedTextView].

I tryed firstResponder for an app and a window, and also fieldEditor:forObject:, but this does not return anything interesting (at least, to me).

By the way, if anybody knows how to get the system wide current text view, that would be even cooler (Accessibility APIs won’t work: it won’t return a Cocoa NSTextView).

Thanks

From stackoverflow
  • The -firstResponder function returns the field editor. So if you want the real view you might need to check the first responder's delegate to get to it. Also see field editor for details.

    There is probably no way to get it system wide as a NSTextViews since that object is in general in a different process space.

    Ilya Birman : Thanks, but what if an app does not use field editor at all? For example, in Pages it returns null. Basically I need to find a current object that responds to selector setInsertionPointColor:. Anything else to try?
    Ilya Birman : Oh, I found that windows’s firstResponder itself usually responds to setInsertionPointColor:, but sometimes it doesn’t (like, in Mail.app it uses some kind of WebView to display message editor).
  • By the way, if anybody knows how to get the system wide current text view, that would be even cooler (Accessibility APIs won’t work: it won’t return a Cocoa NSTextView).

    Not possible. NSTextViews are per-process; you can't get a proxy to an NSTextView from another process without that other process serving it up through an NSConnection. You're just going to have to use Accessibility.

    On the bright side, using Accessibility means your app should (in theory) also work with Carbon apps that use MLTE/HITextView.

0 comments:

Post a Comment