Version 5 of Moving the mouse

Updated 2004-01-30 08:50:26

ulis, 2004-01-29. No, Tcl nor Tk can move your mouse or your hand. But Tk (with the help of Tcl) can move the mouse cursor on your screen. The trick is to use the -warp option of the event generate command. (This trick comes from Kroc).

A little script to illustrate this:

  pack [button .b -text Ok -width 4 -command exit]
  bind . <Key> { set ::stop 1 }
  update
  set stop 0
  set x -20; set y -10; set incrx 1; set incry 0.5
  proc move {} \
  {
    if {$::stop} { return }
    set ::x [expr {$::x + $::incrx}]
    set ::y [expr {$::y + $::incry}]
    if {$::x < 20} \
    { 
      event generate .b <Motion> -warp 1 -x $::x -y $::y
      after 100 move 
    } \
    else \
    { 
      event generate .b <ButtonPress-1>
      after 100 event generate .b <ButtonRelease-1>
    }
  }
  focus -f .
  raise .
  move

See also

  • This is covered in warp

APN The above script didn't seem to do anything as far as I could tell on my Win2K box. Also, is warping restricted to Tk windows only or can the mouse be moved anywhere on the screen (for automation tests for example). An alternative on Windows NT and above is the move_mouse command that is part of TWAPI.

ulis Very surprising: I tested it on a W2k box. Maybe Tk version matters: I used 8.4.

The x & y coords are computed for the Tk widget (.b here) and the cursor can go outside the widget.

In good conditions the script move the cursor mouse from outside the widget to the center of the button.


Category ?