Detect multiple key presses at once?

Is there a way to access all buttons currently pressed?
If not, why? And if there is, how?

2 Likes

Be aware that keyboards cannot read all key presses at the same time. Due either to the way they’re wired or the way the key press data is encoded, some combinations of keys will mask later keys. What’s worse is that it can be different between different keyboards.

You can try this out on your keyboard with this code. On my HP desktop keyboard, for instance, I can only see 3 of the arrow keys at once. Be sure to test this with the key combinations you want before thinking your code might have a bug somewhere else.

boolean[] keysDown;
boolean bHigh = false;

void setup() {
  size( 640, 640 );
  keysDown = new boolean[ 256 ];
}

void draw() {
  background(bHigh ? 128 : 0);
  noStroke();
  fill( 255 );
  for( int j=0; j<16; j++ )
    for( int i=0; i<16; i++ )
      if( keysDown[ j*16+i ] )
        text( str(j*16+i), i*40, j*40 );
}

void keyPressed() {
  if( keyCode < 256 ) 
    keysDown[ keyCode ] = true;
  else bHigh = true;
}

void keyReleased() {
  if( keyCode < 256 ) 
    keysDown[ keyCode ] = false;
  else bHigh = false;
}