【发布时间】:2013-10-26 06:45:23
【问题描述】:
是否可以像使用mouseLocation 获取鼠标光标位置一样全局获取键盘光标(插入符号)的当前位置坐标?
【问题讨论】:
标签: objective-c macos cocoa events keyboard
是否可以像使用mouseLocation 获取鼠标光标位置一样全局获取键盘光标(插入符号)的当前位置坐标?
【问题讨论】:
标签: objective-c macos cocoa events keyboard
不,没有办法在全球范围内这样做。
如果您想在自己的应用程序中执行此操作,例如在 NSTextView 中,您可以这样做:
NSRange range = [textView selectedRange];
NSRange newRange = [[textView layoutManager] glyphRangeForCharacterRange:range actualCharacterRange:NULL];
NSRect rect = [[textView layoutManager] boundingRectForGlyphRange:newRange inTextContainer:[textView textContainer]];
rect 将是所选文本的矩形,或者在只有插入点但没有选择的情况下,rect.origin 是插入点的相对视图位置。
【讨论】:
您可以在 macOS 10.0 及更高版本中轻松完成此操作。
对于NSTextView,覆盖drawInsertionPointInRect:color:turnedOn: 方法。要相对于窗口转换插入符号的位置,请使用convertPoint:toView: 方法。最后,您可以将翻译后的位置存储在实例变量中。
@interface MyTextView : NSTextView
@end
@implementation MyTextView
{
NSPoint _caretPositionInWindow;
}
- (void)drawInsertionPointInRect:(CGRect)rect color:(NSColor *)color turnedOn:(BOOL)flag
{
[super drawInsertionPointInRect:rect color:color turnedOn:flag];
_caretPositionInWindow = [self convertPoint:rect.origin toView:nil];
}
@end
【讨论】:
您可以获得的最接近的方法是使用 OS X 的辅助功能协议。这是为了帮助残障用户操作电脑,但是很多应用程序不支持,或者支持的不是很好。
过程大概是这样的:
appRef = AXUIElementCreateApplication(appPID);
focusElemRef = AXUIElementCopyAttributeValue(appRef,kAXFocusedUIElementAttribute, &theValue)
AXUIElementCopyAttributeValue(focusElemRef, kAXSelectedTextRangeAttribute, &selRangeValue);
AXUIElementCopyParameterizedAttributeValue(focusElemRef, kAXBoundsForRangeParameterizedAttribute, adjSelRangeValue, &boundsValue);
由于对该协议的支持参差不齐,对于许多应用程序,您将无法超越 FocusedUIElementAttribute 步骤,但这确实适用于某些应用程序。
【讨论】: