I simulate a key press on macOS 12 using CGEventKeyboardSetUnicodeString and CGEventPost. Despite creating the key up and down events with the same parameters, the resulting NSEvent for key up has a different character value. Why?
Here is how I generate the key press:
CGEventRef keyDown, keyUp;
UniChar unicode = 'P';
keyDown = CGEventCreateKeyboardEvent(NULL, 0, true);
CGEventKeyboardSetUnicodeString(keyDown, 1, &unicode);
CGEventPost(kCGSessionEventTap, keyDown);
CFRelease(keyDown);
keyUp = CGEventCreateKeyboardEvent(NULL, 0, false);
CGEventKeyboardSetUnicodeString(keyUp, 1, &unicode);
CGEventPost(kCGSessionEventTap, keyUp);
CFRelease(keyUp);
In my first responder, I have:
- (void)keyDown:(NSEvent *)event
{
NSLog(@"%s", [event.characters UTF8String]);
}
- (void)keyUp:(NSEvent *)event
{
NSLog(@"%s", [event.characters UTF8String]);
}
But this prints
2022-09-08 12:04:55.570063-0400 test[14010:5447113] P
2022-09-08 12:04:55.570252-0400 test[14010:5447113] a
Why does the key up event have the character value "a" instead of "P", despite being create with the same parameters?