Trap each SHIFT key independently on OS X
Asked Answered
C

1

0

I have working code (here) that traps keycodes for non-modifier keydown events, and modifier-changed events.

But if you do:

LSHIFT down -> RSHIFT down -> RSHIFT up -> LSHIFT up

... the inner 2 actions will not trigger either of these hooks, because the modifier state is not changing!

(EDIT: Woops! I should have tested that out before writing, because actually a new modifier-changed is produced by each actual change.)

My only thought is maybe to additionally watch at an even lower level (here) -- but that doesn't look pretty no matter which angle I look at it from.

Cavity answered 22/5, 2015 at 10:14 Comment(3)
No, they have separate keycodes -- I confirmed this by executing the code in the second link.Cavity
Assuming you are making a Cocoa app with Obj-C (given the OSX tag) you can use the code here. Implement -(void)flagsChanged:(NSEvent*) and check [theEvent modifiers]. LShift is 131330 and RShift is 131332Horologium
@Arc676, you groover! I've just tested and it does indeed correctly isolate L&R Shift events. Even composites like +L+R-L-R and +L+R-R-L. If you put it as an answer I will happily accept it.Cavity
H
3

Taken from Justin Boo's answer here

I've added some more modifier just in case someone stumbles upon this and wants other keys as well.

- (void) flagsChanged:(NSEvent*)theEvent{
    if ([theEvent modifier] == 131330){
        //do stuff regarding left shift
    }else if ([theEvent modifier] == 131332){
        //do stuff regarding right shift
    }else if ([theEvent modifier] == 65792){
        //caps lock is on
    }else if ([theEvent modifier] == 8388864){
        //FN key pressed
    }else if ([theEvent modifier] == 262401){
        //control key pressed
    }else if ([theEvent modifier] == 524576){
        //option key pressed
    }else if ([theEvent modifier] == 1048840){
        //command key pressed
    }else if ([theEvent modifier] == 256){
        //there are no modified pressed and caps lock is off
    }
}

I recommend storing some BOOLs in your class such as LShiftDown and RShiftDown as this method should be called when the modifiers are pressed. You can probably also detect this property in your keyDown implementation to detect differences such as "a" and "A".

Horologium answered 22/5, 2015 at 12:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.