Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate a Unicode Char "key press" in Mac Os X using Objective-C?

I want to simulate a unicode character in Mac OS X to send to the Foreground application. I mean I have a unicode char(can contain Arabic, Chinese, etc.) like 'a' and I want to input it. Please note that I am not trying to use Virtual Keys or Key Codes. Only a character.

Sincerely yours, Peyman Mortazavi

like image 748
Peyman Avatar asked Apr 16 '12 18:04

Peyman


1 Answers

I found a very good approach but there is still a problem. look at the code then I write what is the current problem.

    CGEventRef downEvt = CGEventCreateKeyboardEvent( NULL, 0, true );
CGEventRef upEvt = CGEventCreateKeyboardEvent( NULL, 0, false );
UniChar oneChar = 'h';
CGEventKeyboardSetUnicodeString( downEvt, 1, &oneChar );
CGEventKeyboardSetUnicodeString( upEvt, 1, &oneChar );
CGEventPost( kCGAnnotatedSessionEventTap, downEvt );
CGEventPost( kCGAnnotatedSessionEventTap, upEvt );

The problem is that this event is limited to some sessions like the search box and this is because kCGAnnotatedSessionEventTap if we change it to kCGSessionEventTap then it will only work on Search Box. Not can you help me to combine them to make it apply this event to every sessions.

Regards, Peyman Mortazavi

like image 196
Peyman Avatar answered Sep 23 '22 15:09

Peyman