Keyboard buttons to remote the values


#1

Hello, sorry for stupid question, but I am still new in programming.
Until now all my apps was handle by mouse or touch board. But now I need to use computer keyboard.
For example I want to increase/decrease some variable by pressing arrow up/down. Or to call some function by pressing “enter” or any other key.
Is there any Juce method to make such thing?
I tried to find something in Juce documentation, but almost all classes or methods with “keyboard” in name concern to midi keyboard. But I just need to use my laptop keyboard. How to do that easly?


#2

Most JUCE components handle keyboard strokes by default (such as moving sliders around with the arrow keys and such), but for custom behavior you can override the keyPressed() method

You can check what keys / modifiers are down using methods of the KeyPress object and then return either true or false based on whether or not your component used that keypress


#3

OK great thanks but how to determine which exactly key was pressed?
I see there are only some functional key indicators, like F1Key, F2KeyF35Key. Or numberPad0 to numberPad9. Or numberPadDelete.
But how to indicate that I pressed for example letter “w” or “W”, or any other letter? Or arrows? Which are most important for me at the moment


#4

If arrows are your most important the easiest way would be something like:

bool myComponent::keyPressed(const KeyPress &key)
{
    if (key == KeyPress::upKey)
    {
        // increase a value or something similar
        ...

        // return true since we consumed the keypress
        return true;
    }

    // the keypress wasn't used by the component
    return false;
}

So you could handle each arrow (KeyPress::upKey, KeyPress::downKey, KeyPress::leftKey, and KeyPress::rightKey) by extending that with else if statements.

If you need to handle characters and/or modifier keys, the most simple & readable way may be to use createFromDescription(). So you could check for control + ‘G’ with something like:

bool myComponent::keyPressed(const KeyPress &key)
{
    if (key == KeyPress::createFromDescription("CTRL + G")
    {
        // do something based on CTRL+G
        ...

        return true;
    }

    return false;
}

For checking against capital letters instead of lowercase you may compare against the letter’s keycode or use KeyPress::getTextCharacter() and compare it as a string

Hope that helps! :slight_smile:


#5

That helps great. Thanks