Monday, July 1, 2013

Control your mouse with Java

Perform all mouse operation with help of java program
You may control your mouse using this simple program.
import java.awt.Robot; 
import java.awt.event.InputEvent; 

/* 
 * To change this template, choose Tools | Templates 
 * and open the template in the editor. 
 */ 
/** 
 * 
 * @author Anurag 
 */ 
public class ControlMouse { 

    public static void main(String args[]) { 
        ControlMouse.control_mouse(); 
    } 

    public static void control_mouse() { 
        try { 
            Robot robot = new Robot(); 
             
            //Move mouse to cordinates x,y 
            robot.mouseMove(300, 550); 
             
            // Perform mouse LEFT CLICK 
            robot.mousePress(InputEvent.BUTTON1_MASK); 
            robot.mouseRelease(InputEvent.BUTTON1_MASK); 
             
            // Perform mouse RIGHT CLICK 
            robot.mousePress(InputEvent.BUTTON3_MASK); 
            robot.mouseRelease(InputEvent.BUTTON3_MASK); 
             

            // SCROLL THE MOUSE WHEEL 
            robot.mouseWheel(-150); 
             
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 

Explaination :
First we make an object of Robot class.
To move the mouse to particular position like x,y use robot.mouseMove(x,y)
To perform left click just perform mouse press and then release operation. For this we use mousePress and mouseRelease methods.BUTTON1_MASK resembles the left button
To perform right click just perform mouse press and then release operation. For this we use mousePress and mouseRelease methods.BUTTON3_MASK resembles the right button
To move mouse wheel use robot.mouseWheel(-150). Here -ve value give upward mouse wheel movement and +ve show downward.
Hope you liked it.. :) 
Cheers,

Ujjwal Soni

No comments: