FREE TRIAL: Accelerate your app development career with 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?

   

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

   

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)

   

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

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.