How to simulate a Unicode Char “key press” in Mac

2019-03-21 13:08发布

问题:

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

回答1:

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