How to send a “Cmd-C” keystroke to the active application in objective-c, or tell the application to do a copy operation?

StackOverflow https://stackoverflow.com/questions/1505933

  •  19-09-2019
  •  | 
  •  

Question

Getting the active application is not a problem, I already have this implemented.

What I want to know is how to send a "Cmd-C" key combination to the active application so it puts the selected text in the clipboard (general pasteboard).

Or even better: how to tell the active application to do a copy operation without sending the keystroke, or without highlighting the "Edit" menu when the copy operation is triggered.

I can't use NSAppleScript (10.2) because this specific class must be as backwards-compatible as possible (down to 10.0 ideally).

I have looked at NSAppleEvents (which would seem the way to go) but can't seem to find a way to do this. A specific answer would be very welcome!

Thanks in advance!

UPDATE:

The NSAppleScript solution by Rob works but I'm still interested in doing this without the need for NSAppleScript. I've tried using CGPostKeyboardEvent (using the last boolean value to set the key to its "up" or "down" status) but I can't seem to find the key codes or any character code tables. Could someone precise how CGPostKeyboardEvent would be used to type a "c"? (a CGCharCode and CGKeyCode table would be perfect).

Was it helpful?

Solution

OTHER TIPS

If you can enable System Events (access for assistive devices) on the computer, you can send this script with an NSAppleEvent [EDIT: actually NSAppleScript] initWithSource:

tell application "System Events" to keystroke "c" using command down

I don't really have any idea when System Events was introduced, though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top