We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi, I have a question about a behaviour of opening a file with the combination of Command key and 'O' key. The code is as below. It almost works, but when I open a file or cancel the dialog box after selectInput() method was called, and then immediately after that trying to open another file by pressing Command+O it just doesn't work. If I press the command key once before pressing Command+O then it works again, so it seems its something to do with Command key. Can anyone tell me what the problem is?
boolean key_command;
boolean key_open;
int COMMAND_KEY = 157; // apple-command key
void setup()
{
size(100, 100);
key_command = false;
key_open = false;
}
void draw()
{
}
void keyPressed()
{
if (key == CODED) {
if (keyCode == COMMAND_KEY) {
key_command = true;
}
}
if (key == 'o' || key == 'O')
key_open = true;
checkComboKeys();
}
void keyReleased()
{
println("keyReleased()");
resetComboKeys();
}
void checkComboKeys() {
if (key_command && key_open) { // command-apple + O
println("command + O pressed");
openFile();
}
}
void resetComboKeys() {
key_command = false;
key_open = false;
}
void openFile() {
selectInput("Select a file to open:", "openSelected");
}
void openSelected(File selection) {
if (selection == null) {
println("Window closed or cancelled.");
} else {
println("User selected: " + selection.getAbsolutePath());
}
}
Answers
Might I suggest resetting the keyCode?
keyCode=0;
aka resetting the keyKode field. It might not work but worth to try. This could be done right after you detect your ctrl+o combination.Kf
Hi kfrajer.
Thank you for your suggestion. I tried it, but it didn't work. It seems the command key wasn't detected in keyPressed() every other time. I also realised that I probably need to use a timer to detect comination keys properly as in the similar manner as detecting double clicks. keyReleased() method should be more like this at least.
though this doesn't resolve the issues above. It seems not as easy as I imagined...
I added a println() in the keyPressed() method as below.
It prints 'key:157' (command key) and 'key:0' alternately with the above program. I wonder if this is a bug or my use of selectInput() is not correct?
Hi all.
I sorted this issue by a bit of working around. The code is as below for a record. It's slightly messy, but it works. I had to detect apple-command key separately. I also added a timer. More lines were required than I imagined. My verdict is that I wouldn't use combination short-cut keys and just use single key for a short cut unless absolutely required.
Please let me know if someone find a better way of doing this. I also don't know why (keyCode == COMMAND_KEY) didn't work alternately. Any idea?