Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I control the mouse cursor from within R?

Is it possible, to control the mouse pointer from the R console?

I have something like this in mind:

move_mouse(x_pos=100,y_pos=200)   # move the mouse pointer to position (100,200)
mouse_left_button_down            # simulate a press of the left button
move_mouse(x_pos=120,y_pos=250)   # move mouse to select something
mouse_release_left_button          # release the pressed button

In MATLAB, something like this is possible with the following code

import java.awt.Robot;
mouse = Robot;
mouse.mouseMove(0, 0);
mouse.mouseMove(100, 200);

I tried a direct conversion of the above into R that looks like this:

install.packages("rJava")          # install package
library(rJava)                     # load package
.jinit()                           # this starts the JVM
jRobot <- .jnew("java/awt/Robot")  # Create object of the Robot class

Once I got jRobot in R, I tried to call its metho "MouseMove(100,200)" using the two command below which both resulted in an error.

jRobot$mouseMove(10,10)

Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  : 
              java.lang.NoSuchMethodException: No suitable method for the given parameters

or

.jcall(jRobot,, "mouseMove",10,10)
Error in .jcall(jRobot, , "mouseMove", 10, 10) : 
              method mouseMove with signature (DD)V not found
like image 305
Bernd Avatar asked Dec 06 '22 04:12

Bernd


2 Answers

Finally I found the problem. You have to tell R that 100 is an integer, in order to pass it to java correctly.

install.packages("rJava")          # install package
library(rJava)                     # load package
.jinit()                           # this starts the JVM
jRobot <- .jnew("java/awt/Robot")  # Create object of the Robot class

# Let java sleep 500 millis between the simulated mouse events
.jcall(jRobot,, "setAutoDelay",as.integer(500))

# move mouse to 100,200 and select the text up to (100,300)         
.jcall(jRobot,, "mouseMove",as.integer(100),as.integer(200))
.jcall(jRobot,, "mousePress",as.integer(16))
.jcall(jRobot,, "mouseMove",as.integer(100),as.integer(300))
.jcall(jRobot,, "mouseRelease",as.integer(16))
like image 94
Bernd Avatar answered Dec 29 '22 22:12

Bernd


As of 2017, CRAN has a package called rMouse to handle mouse movement.

library(rMouse)
move(0,0)       # move to top left corner (0,0)
move(50,30)     # move to pixel x = 50, y = 30
left()          # left click
right()         # right click

Under the hood it still uses Java's robot.

Similarly, KeyboardSimulator package published in 2018 seems to be doing pretty much the same thing

like image 32
OganM Avatar answered Dec 29 '22 22:12

OganM