keyPressed() only works sometimes

I have not seen this particular problem addressed here but maybe I have missed it despite searching. When I try to capture keyboard inputs in Processing (such as with the keyPressed function), the code works about 2/3 of the time. Other times, the code runs but keyboard input is ignored. I run the exact same code over and over and there seems to be no pattern as to when it will work. I’ve tried waiting before typing a key, not waiting, clicking inside the Processing window, etc. I can’t detect a rhyme or reason to why this code works…sometimes.

void setup(){
  size(300,300);
}

void draw(){}


void keyPressed() {
  if (key == CODED) {
    if (keyCode == LEFT){
      background(color(255,0,0));
    } else if (keyCode == RIGHT) {
      background(color(0,0,255));
    } 
  }
}

Hi @beckerc,

I just checked you code and I have no issue on my computer.
Be sure to click inside the window to make it active.

1 Like

Thanks jb4x. I was getting keyboard input to work sometimes without clicking on the window which was throwing me. However, you are right, in that if the code is not responding, clicking on the window will work.

Is there a way to select the window with code so that a user doesn’t have to click the mouse on the window? Asking the user to click before keyboard input is accepted seems a little clumsy. And when running a sketch as an executable and having Processing expand to the whole screen, it seems extra unintuitive that a user has to click the window.

Does anyone have any workarounds for this? It still seems odd that I don’t always have to click inside the Processing window before keyboard is registered, just sometimes.

Thanks,
Christopher

1 Like

Hi @beckerc, was looking for a solution to this issue aswell, couldn’t find one out there but found my own solution that works flawlessly for me, in setup put, surface.setVisible(true);

surface.setVisible(false); will hide the display window but setting it to true makes it active, please let me know if it helps you as i only made an account here to answer your question.

3 Likes