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'm trying to use Mathematica to write small games, and I find that it would help to restrict the player's mouse into the game window (just like other games do). Is there any way to achieve this?

I've tried to use this moveMouse function, but I found it not as efficient as I expected, because what I really want is to restrict the cursor inside the window, not to pull it back. In fact, moving the mouse by this function cannot stop the mouse getting out of the window, it just pulls it back only as the function was executed. So I found it doesn't help much for my purpose. Is there any other method (like another java function?) that can actually restrict the mouse?

share|improve this question
@Silvia Thanks! – Gentleman Meow Apr 1 '14 at 14:58
@Silvia Still in trouble, could you please help me? – Gentleman Meow Apr 3 '14 at 9:09

Using mouseMove from the answer Silvia linked to in her comment:

robotclass = JavaNew["java.awt.Robot"];

DynamicModule[{mousePosG = {0, 0}, mousePosS, screenPos},
        mousePosS = MousePosition[{"ScreenAbsolute", Graphics}, mousePosS]; 
        mousePosG = MousePosition["Graphics", mousePosG]]], 
      PlotRange -> 20, ImageSize -> 200], FrameMargins -> 0, ImageMargins -> 25], ""],
   Row@{Button[ToExpression["\\[" <> "ControlKey" <> "]"], None, 
      Appearance :> If[Dynamic[CurrentValue["ControlKey"]], "Pressed", 
        "DialogBox"]], Dynamic@mousePosG, Dynamic@mousePosS, 
     Dynamic[screenPos = MousePosition["ScreenAbsolute"]],
     DynamicWrapper["", If[screenPos != mousePosS && Not[CurrentValue["ControlKey"]], 
       robotclass[mouseMove[##]] & @@ mousePosS], TrackedSymbols :> {screenPos}]}
   }], Initialization :> (mousePosS = MousePosition["ScreenAbsolute"])


One can replace

  mousePosS = MousePosition[{"ScreenAbsolute", Graphics}, mousePosS]; 
  mousePosG = MousePosition["Graphics", mousePosG]]]

with, e.g.,

 Dynamic[Arrow[{# - {-1.5, 3}, #}] &[
   mousePosS = MousePosition[{"ScreenAbsolute", Graphics}, mousePosS];
    mousePosG = MousePosition["Graphics", mousePosG]]]}

to make the cursor look more familiar.


share|improve this answer
When mouse isn't initially in the box then I can't get there. When it's outside the notebook I can't get to the notebook. Can't investigate more atm. – Kuba Oct 27 '15 at 7:39
@Kuba Now you can escape or get into the box by keeping the Ctrl key pressed. – Karsten 7. Oct 27 '15 at 14:05

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.