I’m wondering if there is a simple way to detect a specific key keyDown (or press) and a keyUp (or release) event ?
For now I’ve inherited from the KeyListener class and implemented keyPressed and keyStateChanged but I’m wondering if there is a easier way of getting those specific events. Because in the keyPressed I think I cannot have access the down or up information and in the keyStateChanged I think I cannot have access to the keycode.
Most apps will only be interested in getting events for a particular key. In this case you override the keyStateChanged method and use KeyPress::isKeyCurrentlyDown() to check if that particular key is up or down.
If you really need to have up/down events for all keys then it’s best to override keyPressed with something that stores a copy of the KeyPress object in some kind of set, and keyStateChanged should then query all the keys in the set - removing them from the set if they are not down anymore.
You need to invert the second if (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey)):
bool CanvasView::keyStateChanged(bool isKeyDown, Component * originatingComponent)
{
if (isKeyDown)
{
if (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey))
{
DBG("SPACE DOWN");
}
}
else
{
// Don't print "SPACE UP" if some other key went up, so check that it's the space key which actually went up
if (! KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey))
{
DBG("SPACE UP"); // never called
}
}
return false;
}
Even better is the following:
bool CanvasView::keyStateChanged(bool isKeyDown, Component * originatingComponent)
{
// it's better if this is a member variable. Using static just for this example here:
static auto lastSpaceKeyIsDown = false;
auto newSpaceKeyIsDown = KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey);
if (newSpaceKeyIsDown != lastSpaceKeyIsDown)
{
lastSpaceKeyIsDown = newSpaceKeyIsDown;
if (newSpaceKeyIsDown) DBG ("Space DOWN");
else DBG ("Space UP");
}
}
Why can’t keyStateChanged simply provide the key/keycode that was changed?
I have to maintain a dictionary just to catch keydown/up events???
How is this a sane API design?
Usually there’s some logic as to why things are the way they are in JUCE but this just makes me scratch my head.