recipes : programming : Programatic control of the mouse

Problem

You want to control the mouse cursor location programatically.

Solution

Controlling the mouse cursor location is both easy and amusing. Just the way get(gcf) returns a handle that allows you alter properties of the current figure, get(0) returns a handle that allows you alter various properties of your Matlab session. Try typing it and see what you have access to. Here's how we can use it to control the mouse:

%Send the mouse cursor to the middle of the screen
pos=get(0,'ScreenSize');
xy=[pos(3)/2,pos(4)/2];
set(0,'PointerLocation',xy)
Discussion

Of course you can also use this approach to read back the position of the cursor and have your program respond appropriately. The following code brings up the word "RIGHT" when the mouse on the right of the screen and "LEFT" when it's on the left. In addition, it uses the backspace character (\b) to write repeatedly to the same line. Much neater that way!

pos=get(0,'ScreenSize');
midx=pos(3)/2;


while 1
    xy=get(0,'PointerLocation');
    if xy(1)>midx
      fprintf('RIGHT')
    else
      fprintf('LEFT ')
    end
 
    pause(0.1)
    fprintf(repmat('\b',1,5))
end