【问题标题】:Get Current Keyboard Cursor Location获取当前键盘光标位置
【发布时间】:2013-10-26 06:45:23
【问题描述】:

是否可以像使用mouseLocation 获取鼠标光标位置一样全局获取键盘光标(插入符号)的当前位置坐标?

【问题讨论】:

    标签: objective-c macos cocoa events keyboard


    【解决方案1】:

    不,没有办法在全球范围内这样做。

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

    【讨论】:

      【解决方案2】:

      您可以在 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
      

      【讨论】:

        【解决方案3】:

        您可以获得的最接近的方法是使用 OS X 的辅助功能协议。这是为了帮助残障用户操作电脑,但是很多应用程序不支持,或者支持的不是很好。

        过程大概是这样的:

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

        由于对该协议的支持参差不齐,对于许多应用程序,您将无法超越 FocusedUIElementAttribute 步骤,但这确实适用于某些应用程序。

        【讨论】:

        • 感谢您的回复。是的,我也在考虑使用 Accessibility API,但之前从未使用过它,所以不知道如何使用它。我正在查看 Apple 的 UIElementInspector 示例代码和文档,试图弄清楚我应该如何做。看起来您所写的内容应该是一个不错的开始方式。
        猜你喜欢
        • 1970-01-01
        • 2012-03-29
        • 2011-09-19
        • 2022-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多