UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How can I programmatically enter text to an arbitrary application/first-responder?

Forums > macOS

I want to make a little tool that can enter some text (like a snippet manager) into the app that is focused. How can I do that?

3      

At the moment I am thinking CGEventCreateKeyboardEvent. I am guessing that is the way to go, here?

3      

This works:

let text = "\(Date())"
let utf16Chars = Array(text.utf16)

let event1 = CGEvent(keyboardEventSource: nil, virtualKey: 0x31, keyDown: true);
event1?.flags = .maskNonCoalesced
event1?.keyboardSetUnicodeString(stringLength: utf16Chars.count, unicodeString: utf16Chars)
event1?.post(tap: .cghidEventTap)

let event2 = CGEvent(keyboardEventSource: nil, virtualKey: 0x31, keyDown: false);
event2?.flags = .maskNonCoalesced
event2?.post(tap: .cghidEventTap)

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.