2013-04-29 91 views
2

我正在嘗試創建一個OSX應用程序,它將成爲屏幕鍵盤的複製品。是否可以將某些文本插入到另一個活動應用程序的光標位置?提前致謝!如何在Mac OSX應用程序(如OSK)上的其他應用程序的光標位置插入文本?

+1

僅供參考,以防萬一:答案(無論細節,對不起,我不知道它們)是一個*合格*是 - 例如,這是輔助軟件的工作原理。 *但是*在沙箱下,因此在App Store中,一般的答案肯定是否定的 - 輸入到另一個應用程序可能是一個嚴重的安全問題。當然,如果您的應用程序不在沙箱中,那麼它的限制就不會有問題。 – CRD 2013-04-29 18:55:21

+0

@CRD沙盒的含義是什麼。你的意思是說,如果我提交應用程序到appstore它不會工作?但作爲一名蘋果開發人員,我可以在我的系統中運行這個應用程序?你可以請詳細說明..謝謝。 – Selvin 2013-04-30 09:01:37

+1

應用程序沙箱是一個安全系統,它限制了應用程序可以執行的操作 - 可以訪問哪些文件,是否可以進行網絡連接等。所有iOS應用程序都是沙盒,對於OS X,它是可選的。但是,所有在Mac App Store中銷售的應用程序都必須進行沙盒處理。在Apple文檔中查找App Sandbox瞭解詳細信息。 – CRD 2013-04-30 10:13:32

回答

1

不知道這是否會有所幫助,但在AppleScript的,你可以這樣做

tell application "System Events" 
    keystroke "Stuff here" 
end tell 

因此,也許你可以嘗試調用使用NSApplescript或使用NSTask可可內運行

osascript -e 'tell application "System Events" to keystroke "Stuff here"' 
+0

這也不適用於Mac App Store,因此您最好澄清一下。 – SevenBits 2014-02-26 13:41:13

5

這是可能。輔助功能可以更改其他應用程序的內容,但是您的應用程序不能被沙箱化,因此無法通過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); 
} 

此代碼不檢查錯誤,並假定焦點元素是文本區域。

相關問題