0

How would you simulate the keystroke ö on Mac OS X programmatically?

This isn't just a randomly chosen character, I know you can simulate all ASCII characters as well as some special ones like Esc, Backspace, etc using either an embedded Applescript or CGEventCreateKeyboardEvent. But what about all those keys for which a CGKeyCode isn't defined? There must be a way!

kaiz.net
  • 1,984
  • 3
  • 23
  • 31
lmirosevic
  • 15,787
  • 13
  • 70
  • 116
  • The accepted answer to this question (http://stackoverflow.com/q/1918841/3009) is probably what you are looking for. – highlycaffeinated Sep 21 '12 at 14:53
  • @highlycaffeinated I read the source code you mentioned but it only works for ASCII, I need keycodes for chars like `õ`, `ñ`, `é`, `č`, etc. – lmirosevic Sep 21 '12 at 15:12
  • 4
    There's no single keycode for accented characters. Normal input of them requires multiple keypresses, and so does simulated input. You should also look at [CGEventKeyboardSetUnicodeString()](https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html#//apple_ref/doc/uid/TP40003550-CH202-DontLinkElementID_10) – jscs Sep 21 '12 at 16:51
  • @JoshCaswell, I think `CGEventKeyboardSetUnicodeString` is the right answer, you should post that as an answer. – JWWalker Sep 21 '12 at 18:08
  • `tell application "System Events" to keystroke "ö"` would work if the German keyboard layout was selected. Some keyboard layouts have separate keys (and key codes) for Latin characters with diacritics. – Lri Sep 22 '12 at 06:20
  • id of only gives the decimal code point of a character. How could it be used to emulate keystrokes? – Lauri Ranta - You're right! – adayzdone Sep 22 '12 at 12:57

1 Answers1

2

You need to use CGEventSetFlags to set the option modifier of a 'u' key stroke followed by an up key event and then followed by an 'o' key stroke.

https://developer.apple.com/library/mac/#documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html

If you need more info ask and I will create some code example

Nathan Day
  • 5,981
  • 2
  • 24
  • 40
  • I see. Is it feasible to do this for an arbitrary UniChar? I mean is there a function, or at least a table which maps unicode characters to keystrokes with optional modifiers? – lmirosevic Sep 23 '12 at 18:26
  • Not that I know off, if you go to my https://github.com/nathanday/ndhotkeyevent, it contains a class called NDKeyboardLayout that converts ASCII characters into keyboard key codes, you could look at to get some ideas perhaps. – Nathan Day Sep 23 '12 at 23:59