2013-11-01 73 views
3

是否有可能從R控制檯控制鼠標指針?我可以從R內控制鼠標光標嗎?

我想到的是這樣的:

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 

在MATLAB中,這樣的事情是有可能用下面的代碼

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

我試過上述直接轉換成R,看起來像這樣:

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 

一旦我在R中得到jRobot,我試圖調用它的方法「MouseMove( 100,200)「使用下面的兩個命令導致錯誤。

jRobot$mouseMove(10,10) 

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

.jcall(jRobot,, "mouseMove",10,10) 
Error in .jcall(jRobot, , "mouseMove", 10, 10) : 
       method mouseMove with signature (DD)V not found 

回答

3

最後我發現了這個問題。你必須告訴R 100是一個整數,以便正確地將它傳遞給java。

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)) 
2

什麼操作系統?在Linux中,您可以使用xdotool並從R system函數中調用它。

> mousemove=function(x,y){system(paste0("xdotool mousemove ",x," ",y))} 
> mousemove(0,0) 
> mousemove(500,500) 

注意這些是屏幕座標,與R圖形窗口中的座標無關,但您不清楚您想要什麼。如果這是你想要的,你可能能夠將R圖形窗口的屏幕座標與其他X11實用程序並且放置在一個繪圖上。

在Windows中,可能有一些其他鼠標調整程序可以吸引。 IDK。

xdotool信息:http://tuxradar.com/content/xdotool-script-your-mouse

該條進一步閱讀說明如何激活特定的窗口和他們做鼠標操作。

+0

不幸的是,我必須在Windows機器上:-( 運行此,但我得到你的想法,我可以在.NET例如寫一個小程序,把它編譯成一個.exe,並使用它運行「system」command in R. 我的想法正確嗎? –

+0

是的 - 如果你編寫C++,你可以使用Rcpp,以更綜合的方式調用它,然後把它放在一個包中,你必須在操作系統級別,但沒有R函數可以做到這一點 – Spacedman

+0

這是一個絕對可行的解決方案,但我仍然有些希望直接從R得到外部方法。使用例如java.awt.robot接縫對我來說更加優雅。 –

相關問題