4
$\begingroup$

Consider the following code:

timesXpressed = 0;
SetOptions[EvaluationNotebook[], 
 NotebookEventActions -> {{"KeyDown", "x"} :> timesXpressed++}]
Dynamic[timesXpressed]

It counts the number of times the key x is pressed. However, in intercepting the key presses, they're no longer actually typed in the notebook. I suspect adding an additional action to type x in the notebook when the key is down might fix this, but I don't know such an action.

$\endgroup$
2
  • $\begingroup$ I cannot replicate this behavior on v12.2.0 Win7-x64. Only when "x" is pressed in the notebook does it change the timesXpressed. Please run $Version and include this information. $\endgroup$
    – Syed
    Nov 21, 2021 at 12:54
  • $\begingroup$ ref/NotebookEventActions/Details: The default behavior can be changed by including rules for PassEventsDown or PassEventsUp in the list given as the setting for NotebookEventActions. $\endgroup$
    – rnotlnglgq
    Nov 21, 2021 at 13:10

1 Answer 1

5
$\begingroup$
timesXpressed = 0;
SetOptions[EvaluationNotebook[], 
 NotebookEventActions -> {{"KeyDown", "x"} :> (timesXpressed++; 
     FrontEndExecute[NotebookWrite[InputNotebook[], "x"]])}]
Dynamic[timesXpressed]
$\endgroup$
3
  • $\begingroup$ This is exactly what I was looking for. Thanks. $\endgroup$ Nov 21, 2021 at 14:18
  • $\begingroup$ Is there any way to do logical combinations on these events, for example an action when {"KeyDown", "x"} or {"KeyDown", "X"} ? $\endgroup$ Nov 21, 2021 at 17:38
  • 1
    $\begingroup$ Just add another Keydown action, e.g. NotebookEventActions -> {{"KeyDown", "x"} :> (timesX... , "x"]), {"KeyDown", "X"} :> (timesX... , "X"])} $\endgroup$ Nov 21, 2021 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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