Hello, I want to run some code and then quit the program from running when I press ctrl+x. I tried the next code:
boolean ctrl;
boolean x;
void setup() {
//Some code
}
void draw(){
//More code
}
void keyPressed() {
if (key == CODED) {
if (keyCode == CONTROL){
ctrl = true; //When ctrl is pressed, I set its variable as true.
println("ctrl pressed");
}
}
if (key == 'x' || key == 'X') {
x = true; //The same as ctrl with x.
println("x pressed");
}
if (ctrl && x) {
println("Exiting...\n\n"); //If both keys are pressed, it should print this message and quit.
exit();
}
}
void keyReleased() {
if (key == CODED) {
if (keyCode == CONTROL) {
ctrl = false;
println("ctrl released");
}
}
if (key == 'x' || key == 'X') {
x = false;
println("x released");
}
}
When I run this, if I press x and then ctrl (in that order), it works. But if I do the opposite thing (ctrl first, and then x), it doesn’t do anything. I don’t know why do this happen or how to solve this, can any of you help me?
In case someone is interested, I found a different way to solve it (which is quite more complex than th75’s one, and probably less optimized). Instead of checking if the key is the ASCII code for CAN. I worked with Java keyCodes. Checking if both ctrl and the keyCode 88 (Java code for ‘x’) are pressed:
void keyPressed() {
if (key == CODED) {
if (keyCode == CONTROL){
ctrlPressed = true;
println("ctrl pressed");
}
}
if (ctrlPressed && keyCode == 88) {
//Code
}
}
void keyReleased() {
if (key == CODED) {
if (keyCode == CONTROL) {
ctrlPressed = false;
println("ctrl released");
}
}
}