0

I have bindings that insert text into the current application as a sequence of keypresses. Each keypress is executed by:

https://github.com/sboosali/workflow-osx/blob/master/cbits/objc_workflow.m#L115

e.g. "A" becomes (0x00020000, 0x00) (i.e. (ShiftModifier, AKey)).

However, this has limitations, such as filtering away Unicode characters. Rather than "indirectly" inserting text via keypresses, how could I "directly" insert text, including arbitrary Unicode?

Alternatives:

  1. A subset of Unicode could be supported with the Option modifier, as capital letters are supported with the Shift modifier. However, it's only a subset.

  2. Inserting text via the clipboard supports all of Unicode. However, this overwrites the previous clipboard contents, and needs a variable-length delay.

(I've been reading through the documentation (like https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSTextInputClient_Protocol/index.html#//apple_ref/occ/intfm/NSTextInputClient/insertText:replacementRange:), but I can't seem to get a hold of any of the objects I would need (like NSTextInputClient)).

sam boosalis
  • 1,997
  • 4
  • 20
  • 32

1 Answers1

0

found it, use CGEventKeyboardSetUnicodeString:

// UniChar is a UTF8 codepoint.
insertChar(UniChar c) {

 UniChar cs[1];
 cs[0] = c;

 CGEventSourceRef s = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
 CGEventRef e = CGEventCreateKeyboardEvent(s, 0, true);

 CGEventKeyboardSetUnicodeString(e, 1, cs);   

 CGEventPost(kCGHIDEventTap, e);    

 CFRelease(s);
 CFRelease(e);
}

https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/#//apple_ref/c/func/CGEventKeyboardSetUnicodeString

How send unicode character to active application?

Community
  • 1
  • 1
sam boosalis
  • 1,997
  • 4
  • 20
  • 32