Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to do something when the mouse is clicked. But it shouldn't matter where the mouse is clicked, so I can't use EventHandler. Instead, I'm trying to do it like this:

DynamicModule[{i = 0},
 WhenEvent[ControllerState["Button 1"], i = i + 1]

WhenEvent is not the right function. What I want is a function that will do something when ControllerState["Button 1"] switches from false to true.

share|improve this question
Try this: DynamicModule[{i = 0}, Dynamic[If[ControllerState["Button 1"], (i = i + 1)]; i]]. I think you'll find it doesn't quite behave right. It's really more like a mouse-down event, than a mouse-click. Perhaps that's what you want – Michael E2 Mar 17 '13 at 21:09
No, it must only count one click one time. This is part of the problem. – C. E. Mar 17 '13 at 21:10
There's no such thing as a dynamic variable. Dynamic only keeps some visible output up to date. So, whatever you do with Dynamic, in the best case scenario it will only work when it is visible. Is that what you want? – Rojo Mar 17 '13 at 21:12
If so, you can tweak @MichaelE2's suggestion to "remember" the last check result so it is only triggered in an appropriate change of state. If the behaviour is at notebook level, you can more simply use NotebookEventActions, or NotebookDynamicExpression – Rojo Mar 17 '13 at 21:14
Well... there will be a dynamic component to it. I will click a mouse, and it will change some variables and this will result in a graph of mouse clicks over time. It will be system wide, not on the notebook level. – C. E. Mar 17 '13 at 21:17
up vote 3 down vote accepted

I was just working along the lines of @Rojo's comment:

DynamicModule[{i = 0, state = False}, 
 Dynamic[If[ControllerState["Button 1"], 
   If[state, i = i + 1; state = False], If[! state, state = True]]; i]

Sometimes it appears that the mouse action is intercepted by Mathematica. You may find that unnacceptable.

share|improve this answer
It doesn't seem to be intercepted for me. Works well, thank you. – C. E. Mar 17 '13 at 21:21
You might wait to see what other answers you might get before accepting. – Michael E2 Mar 17 '13 at 21:24
OK, I unmarked temporarily but I'm satisfied with this solution. Will accept it later if I there isn't a way better solution. – C. E. Mar 17 '13 at 21:26

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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