获取当前键盘光标位置

时间:2013-10-17 16:38:56

标签: objective-c macos cocoa events keyboard

无论如何都要获得全局键盘光标(插入符号)当前位置的坐标,就像使用mouseLocation的鼠标光标位置一样?

3 个答案:

答案 0 :(得分:2)

不,全球无法做到这一点。

如果您想在自己的应用中执行此操作,例如在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是插入点的视图相对位置。

答案 1 :(得分:0)

您可以获得的最接近的是使用OS X的辅助功能协议。这是为了帮助残疾用户操作计算机,但许多应用程序不支持它,或者不支持它。

程序如下:

appRef = AXUIElementCreateApplication(appPID);
focusElemRef = AXUIElementCopyAttributeValue(appRef,kAXFocusedUIElementAttribute, &theValue)
AXUIElementCopyAttributeValue(focusElemRef, kAXSelectedTextRangeAttribute, &selRangeValue);
AXUIElementCopyParameterizedAttributeValue(focusElemRef, kAXBoundsForRangeParameterizedAttribute, adjSelRangeValue, &boundsValue);

由于对协议的支持很多,对于许多应用程序,您不会超越FocusedUIElementAttribute步骤,但这适用于某些应用程序。

答案 2 :(得分:0)

您可以在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
相关问题