I would like to let a boolean variable switch when I press a key on the keyboard.

For example, I write

activateE := Block[{}, edown = True;];
SetOptions[EvaluationNotebook[], NotebookEventActions -> {{"KeyDown", "e"} :> activateE}]

and then try to monitor the key presses via

edown = False;

While the key e now stops producing any text input into the notebook, unfortunately the Dynamic always keeps showing False, regardless how often I press the key e. What am I doing wrong, or how to do this properly?


Alternatively, I am trying the CurrentValue function. For example,


properly shows e.g. when the Ctrl key is being pressed. But if I try


the output is None no matter which key I press. Is there an option of CurrentValue that would register a regular key press, like letter e?


What seems to work, is

EventHandler[InputField[], {"KeyDown", "e"} :> activateE]

but only if I first click on the InputField to bring it into focus.

  • $\begingroup$ Use {{"KeyDown", "e"} :> activateE instead. $\endgroup$ – Carl Woll Aug 16 '20 at 16:16
  • $\begingroup$ @CarlWoll Trying this, unfortunately I do not observe any difference in behavior. Does it work on your system? (I'll change the question to reflect this.) $\endgroup$ – Kagaratsch Aug 16 '20 at 16:20
  • $\begingroup$ try NotebookEventActions -> {{"KeyDown", "e"} :> activateE, PassEventsUp -> True}? $\endgroup$ – kglr Aug 16 '20 at 16:40
  • $\begingroup$ It works fine for me in 11.1, 11.3 and 12.1. Maybe it is an OS thing? $\endgroup$ – Carl Woll Aug 16 '20 at 16:42
  • $\begingroup$ This is strange, I'm on 11.3 Windows 10 and both suggestions above do not change the behavior. What seems to work though is EventHandler[InputField[], {"KeyDown", "e"} :> activateE], but only if I first click on the InputField to bring it into focus. $\endgroup$ – Kagaratsch Aug 16 '20 at 16:44

Using NotebookEventActions with the option PassEventsUp -> True gives the desired behavior in Version 11.3 (Windows 10 - 64 bit):

activateE:=  Block[{}, edown = True;];
 NotebookEventActions -> {{"KeyDown", "e"} :> activateE, PassEventsUp -> True}]

enter image description here

A variation: Toggle between False and True when key e is pressed:

enter image description here


"11.3.0 for Microsoft Windows (64-bit) (March 7, 2018)"

  • $\begingroup$ Not sure what's wrong with my system, but normally this clearly seems to work. $\endgroup$ – Kagaratsch Aug 16 '20 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.