# Detecting change of a variable (detect mouse clicks)

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]
i]


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.

-
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. –  Pickett 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. –  Pickett Mar 17 '13 at 21:17

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.

-
It doesn't seem to be intercepted for me. Works well, thank you. –  Pickett 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. –  Pickett Mar 17 '13 at 21:26