如何在Mac OSX应用程序(如OSK)上另一个应用程序的光标位置插入文本? [英] How to insert text at cursor position of another application on Mac OSX Application (like OSK)?

查看:292
本文介绍了如何在Mac OSX应用程序(如OSK)上另一个应用程序的光标位置插入文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建OSX应用程序,该应用程序将是屏幕"键盘的副本.是否可以在其他活动应用程序的光标位置插入一些文本?预先感谢!

I'm trying to create an OSX application which would be a replica of On Screen keyboard. Is it possible to insert some text into the cursor position of another active application? Thanks in advance!

推荐答案

有可能.可访问性使您能够更改其他应用程序的内容,但是您的应用程序无法被沙盒化,因此无法通过AppStore使用.

It is possible. Accessibility enables to change content of other applications, but your app can't be sandboxed and thus not available via AppStore.

CFTypeRef focusedUI;
AXUIElementCopyAttributeValue(AXUIElementCreateSystemWide(), kAXFocusedUIElementAttribute, &focusedUI);

if (focusedUI) {
    CFTypeRef textValue, textRange;
    // get text content and range
    AXUIElementCopyAttributeValue(focusedUI, kAXValueAttribute, &textValue);
    AXUIElementCopyAttributeValue(focusedUI, kAXSelectedTextRangeAttribute, &textRange);

    NSRange range;
    AXValueGetValue(textRange, kAXValueCFRangeType, &range);
    // replace current range with new text
    NSString *newTextValue = [(__bridge NSString *)textValue stringByReplacingCharactersInRange:range withString:newText];
    AXUIElementSetAttributeValue(focusedUI, kAXValueAttribute, (__bridge CFStringRef)newTextValue);
    // set cursor to correct position
    range.length = 0;
    range.location += text.length;
    AXValueRef valueRef = AXValueCreate(kAXValueCFRangeType, (const void *)&range);
    AXUIElementSetAttributeValue(focusedUI, kAXSelectedTextRangeAttribute, valueRef);

    CFRelease(textValue);
    CFRelease(textRange);
    CFRelease(focusedUI);
}

此代码不检查错误,并假设焦点所在的元素是文本区域.

This code does not check for errors and makes assumption that focused element is text area.

这篇关于如何在Mac OSX应用程序(如OSK)上另一个应用程序的光标位置插入文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆