How to Select Last N Characters in Active Text Field Across macOS on Specific Key Binding?

81 Views Asked by At

I'm developing a native macOS application and need assistance with a feature where pressing a specific key combination (e.g., CTRL + S) captures the last N characters (for instance, 200 characters) from whatever text field is active, regardless of the application. This feature should work across all text input fields in any application running on macOS.


I am aware of this solution, where the text that the user has selected manually can be processed by calling the below function (Get selected text when in any application on macOS)

import ApplicationServices
import Cocoa

func getSelectedText() -> String? {
    let systemWideElement = AXUIElementCreateSystemWide()

    var selectedTextValue: AnyObject?
    let errorCode = AXUIElementCopyAttributeValue(systemWideElement, kAXFocusedUIElementAttribute as CFString, &selectedTextValue)
    
    if errorCode == .success {
        let selectedTextElement = selectedTextValue as! AXUIElement
        var selectedText: AnyObject?
        let textErrorCode = AXUIElementCopyAttributeValue(selectedTextElement, kAXSelectedTextAttribute as CFString, &selectedText)
        
        if textErrorCode == .success, let selectedTextString = selectedText as? String {
            return selectedTextString
        } else {
            return nil
        }
    } else {
        return nil
    }
}

So essentially, I need a mechanism that auto-selects previous N words/chars when a certain key-binding was used and then calls the above function getSelectedText().

I am thankful for any help regarding this matter!

0

There are 0 best solutions below