Detecting combinations of SHIFT and CONTROL keys (solved)

Hello everyone,

I wanted to share a quick code snippet to the community. Here’s how to detect when a user holds the shift key or the control key, or both:

// Correct, works fine
bool shift_key = ((e.mods & RACK_MOD_MASK) & GLFW_MOD_SHIFT);
bool control_key = ((e.mods & RACK_MOD_MASK) & GLFW_MOD_CONTROL);

It took me a moment to figure this out. My original code looked like:

// WRONG: DOES NOT WORK
bool shift_key = ((e.mods & RACK_MOD_MASK) == GLFW_MOD_SHIFT);
bool control_key = ((e.mods & RACK_MOD_MASK) == GLFW_MOD_CONTROL);

The latter does not work in the case when both SHIFT and CONTROL are held simultaneously.

I’m just logging this in case others run across the same situation.

4 Likes

There’s some flaw in my code that has me baffled:

bool shift_key = ((e.mods & RACK_MOD_MASK) && GLFW_MOD_SHIFT);
bool control_key = ((e.mods & RACK_MOD_MASK) && GLFW_MOD_CONTROL);

 if(control_key) DEBUG("control key is set");

This code is in a widget, in the onHoverKey() method. If I hold the shift key while mousing-over the widget, then the bool control_key is TRUE and the debug text is output to the log. Any ideas why this might be?

// Here's the definition of RACK_MOD_MASK 
#define RACK_MOD_MASK   (GLFW_MOD_SHIFT | GLFW_MOD_CONTROL | GLFW_MOD_ALT | GLFW_MOD_SUPER)
// which is 1111 in binary

// Here's the definition of GLFW_MOD_SHIFT (according to https://www.glfw.org/docs/3.3/group__mods.html#ga14994d3196c290aaa347248e51740274)
#define GLFW_MOD_SHIFT   0x0001
// which is 000 0001 in binary

// Here's the definition of GLFW_MOD_CONTROL
#define GLFW_MOD_CONTROL   0x0002
// which is 0000 0010 in binary

// Here's my calculation for the control key flag again:
bool control_key = ((e.mods & RACK_MOD_MASK) && GLFW_MOD_CONTROL);

// Swapping the binary values in for the known variables gives:
bool control_key = ((e.mods & 0b1111) && 0b0010);

// This seems good on paper?

Thanks,
Bret

Oh, silly me, I was using && instead of the binary operator &. Woops!

// Updated, hopefully correct this time, code:
bool shift_key = ((e.mods & RACK_MOD_MASK) & GLFW_MOD_SHIFT);
bool control_key = ((e.mods & RACK_MOD_MASK) & GLFW_MOD_CONTROL);