G4P: how to prevent ESC-Key

Hi,
I recently discovered that you can stop the ESC-key from closing your program with this code:

void keyPressed() {
  if (key == ESC) {
    key = 0;
  }
}

However when I open a second window with G4P this only works in the main window, since keyPressed() is only called when a key is pressed and the main window is currently selscted.

What I want to do is prevent the user from accidentaly exiting the program by pressing the ESC-key in the second window. Is there a way?

1 Like

Same question for the dispose() method, which seems not to be called.

you can add keyhandler: like in example
G4P_WindowsStarter

window[i].addKeyHandler(this, "windowKey");

for the main window you used like

void keyPressed() {
  if (key == ESC) {
    key = 0;
    println("main window ESC key / DO NOTHING");
  }
}

for the key press ( into active subwindow )

public void windowKey(PApplet appc, GWinData data, KeyEvent event) {
 //   MyWinData data3 = (MyWinData)data;
 if ( event.getAction() == KeyEvent.PRESS ) {
   println("a key pressed");
   if (appc.keyCode == ESC) {
     println("sub window ESC key / DO NOTHING ");
     appc.key = 0;                  // but better ask if want close window?
  }  
}
}
2 Likes

Hi,
sorry it took a while to implement this, but now I can report: It works great.

Thank you.


For those who are curious, dispose(); works like this:

  1. Set the “Action on Close” in the G4P Tool to “Close Window” to call the handler when the window is closed when [x] is pressed.

  2. Link a method that will be called in the case of closing the window:

setup_window.addOnCloseHandler(this, "setup_windowClose"); // my window is called setup_window
  1. This method will then be called:
public void setup_windowClose(GWindow gwin) { // needs a gwindow which represents the closed window
  exit(); // I use exit here to also close the main window when the secondary is closed
  println("closed secondary");
}

@kll

Thank you

Thanks, it worked out well.