NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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 MadMachine

SPONSORED Want to try Swift on microcontrollers? MadMachine provides ways to interact with the physical world in a Swift way. Join us and have fun!

Get it now

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.