Question

this is my first post so please let me know if anything needs editing.

I currently have a function that will return the virtual key code of an Apple keyboard by passing it a char; CGKeyCode keyCodeForChar(), it works and I have checked the results against various web sources.

A local string such as NSString *myString = @"Hello World!", is broken down and each char processed, CGKeyCode retrieved and attempted to be written using CGEventPost(). This works, however in my attempt to detect the correct flags for when a letter should be capitalised, the entire string is printed out as lower case. This is my code so far:

NSString *myString = @"Hello World!";
if (![self.view.window isKeyWindow])
{
    for (int i = 0; i < myString.length; i++)
    {
        char c = [theString characterAtIndex:i];
        CGKeyCode keyCode = keyCodeForChar(c);

        CGEventRef event;
        CGEventFlags flags = kCGEventFlagMaskShift;
        CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);

        // Key down event
        event = CGEventCreateKeyboardEvent(source, keyCode, true);
        CGEventSetFlags(event, (flags & CGEventGetFlags(event)));
        CGEventPost(kCGHIDEventTap, event);
        CFRelease(event);

        // Key up event
        event = CGEventCreateKeyboardEvent(source, keyCode, false);
        CGEventSetFlags(event, (flags & CGEventGetFlags(event))); 
        CGEventPost(kCGHIDEventTap, event);
        CFRelease(event);

        CFRelease(source);
    }
}

Currently the output is hello world1, the 1 coming from the same CGKeyCode as '!'. Therefore I believe my detecting of the correct flag mask is wrong. I have looked at similar questions asked here such as:

Obtaining modifier key pressed in CGEvent tap

CGEventPost - possible bug when simulating keyboard events?

However the solutions there haven't worked for me, if anyone could help me with where I am going wrong that would be brilliant!

Thank you, Craig

Was it helpful?

Solution

For future searchers: Should be (flags | CGEventGetFlags(event)) not & ... other wise shift is only applied if shift is already applied.

As for determining WHEN the shift should be pressed, your keyCodeForChar function should be also providing that additional information, similar to VkKeyScan() does on Windows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top