MyTetra Share
Делитесь знаниями!
карты на сайте ubergru77.
Как программно нажать клавишу в MacOs
Время создания: 27.09.2011 22:21
Текстовые метки: macos, клавиатура
Раздел: Компьютер - MacOs - Готовые решения
Запись: xintrea/mytetra_syncro/master/base/13171477114l1pqbyowj/text.html на


I'm writing an app where I need to simulate key press events on a mac, given a code that represents each key. It seems I need to use the CGEventCreateKeyboardEvent function to create the event. The problem is that this function needs a mac keycode, and what I have is a code that represents the specific key. So, for example, I recieve:

KEY_CODE_SHIFT or KEY_CODE_A - these are both numeric constants defined somewhere.

I need to take these constants and turn them into CGKeyCode values.

My current attempt uses code similar to this SO question. The problem is that it only works for printable characters. If all else fails, I'm not above hard coding the conversion, but that would mean that I'd need a table of possible CGKeyCode values, which I have not yet been able to find.

Any ideas?


Here's code to simulate a Cmd-S action:

CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);

CGEventRef saveCommandDown = CGEventCreateKeyboardEvent(source, (CGKeyCode)1, YES);

CGEventSetFlags(saveCommandDown, kCGEventFlagMaskCommand);

CGEventRef saveCommandUp = CGEventCreateKeyboardEvent(source, (CGKeyCode)1, NO);

CGEventPost(kCGAnnotatedSessionEventTap, saveCommandDown);

CGEventPost(kCGAnnotatedSessionEventTap, saveCommandUp);




A CGKeyCode is nothing more than an unsigned integer:

typedef uint16_t CGKeyCode; //From CGRemoteOperation.h

Your real issue will be turning a character (probably an NSString) into a keycode. Fortunately, the Shortcut Recorder project has code that will do just that in the SRKeyCodeTransformer.m file. It's great for transforming a string to a keycode and back again.

Q: So in this example then, the CGKeyCode of 1 is the code for S? Also, would this work for just a foreground app, or if it was running in the background, would it work across the entire session?

A: yes to all of those.

Q: So, say my app was running in the background (just as a service) and i had Photoshop in front, i could simulate a key press, and it would be seen in Photoshop?

A: yes, that's what would happen.

MyTetra Share v.0.59
Яндекс индекс цитирования