Skip to content

Instantly share code, notes, and snippets.

@francisfeng
Last active January 12, 2021 03:11
Show Gist options
  • Save francisfeng/c92c82251157d8b61f9f13da3494f7d2 to your computer and use it in GitHub Desktop.
Save francisfeng/c92c82251157d8b61f9f13da3494f7d2 to your computer and use it in GitHub Desktop.
Simulating Command + C (aka Copy command) in macOS
// 0x08 is key code for "c"
guard let keydownEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0x08, keyDown: true) else { return }
guard let keyupEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0x08, keyDown: false) else { return }
keydownEvent.flags = CGEventFlags.maskCommand
keydownEvent.post(tap: CGEventTapLocation.cghidEventTap)
keyupEvent.flags = CGEventFlags.maskCommand;
keyupEvent.post(tap: CGEventTapLocation.cghidEventTap)
// For it to work, Accessibility needs to be enabled in
// System Preferences -> Security & Privacy -> Privacy -> Accessibility.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment