Search code examples
javascriptmouseeventkeyboard-eventsextendscriptadobe-scriptui

How do I detect if a button was clicked with a keyboard key pressed? (Ctrl-click, Alt-click etc.)


I'm trying to write a UI for an Adobe After Effects script. I want to add a functionality where a user can CTRL click a button instead of just clicking it with no keypresses to get a slightly different behavior.

The problem is, however, I don't to know how to detect if a key was pressed when the button was clicked.

I've managed to detect a keypress with

myPanel.addEventListener("keydown", function (kd) {alert(kd.keyIdentifier); return(kd.keyIdentifier);});

This piece of code adds a listener that alerts me a name of the button when it is being pressed. I also have a button onClick event to control what happens when a button is pressed. However, I can't figure out how to combine those two listeners and get an information about whether a key was pressed during the button click. I tried to place the keydown listener inside the onClick function, but then it doesn't work at all.


Solution

  • I managed to make it work.

    The Adobe ScriptUI environment lets you monitor the keyboard status at all times using the Keyboard state object. You can get it from: ScriptUI.environment.keyboardState. It has properties such as altKey, ctrlKey and so on that return a boolean based on whether they key was pressed or not. All you have to do is put the object initiation into the onClick event of the button:

    button.onClick = function() {
        isCtrlPressed = ScriptUI.environment.keyboardState.ctrlKey;
    }
    

    For more information, I refer to p.155 of the Adobe JavaScript Tools Guide