Mathematica Asked by Kagaratsch on October 5, 2020
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;
Dynamic[edown]
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?
EDIT:
Alternatively, I am trying the CurrentValue
function. For example,
Dynamic[CurrentValue["ModifierKeys"]]
properly shows e.g. when the Ctrl
key is being pressed. But if I try
Dynamic[CurrentValue["EventKey"]]
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
?
EDIT2:
What seems to work, is
EventHandler[InputField[], {"KeyDown", "e"} :> activateE]
but only if I first click on the InputField to bring it into focus.
Using NotebookEventActions
with the option PassEventsUp -> True
gives the desired behavior in Version 11.3 (Windows 10 - 64 bit):
ClearAll[activateE]
activateE:= Block[{}, edown = True;];
SetOptions[EvaluationNotebook[],
NotebookEventActions -> {{"KeyDown", "e"} :> activateE, PassEventsUp -> True}]
A variation: Toggle between False
and True
when key e
is pressed:
$Version
"11.3.0 for Microsoft Windows (64-bit) (March 7, 2018)"
Correct answer by kglr on October 5, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP