How To Press Mouse Programmatically

By bhagwatchouhan
How To Press Mouse Programmatically

In this post, we will discuss how to handle mouse presses programmatically without manual intervention. This is sometimes handy when we need to perform a mouse click using the program.

Below mentioned is the code snippet showing the mouse press using Java's in-built awt class Robot.

// Create instance of Robot Class
Robot bot = new Robot();
// Move the bot position to given coordinates
bot.mouseMove( x, y );
// Press and Release the mouse to simulate click
bot.mousePress( InputEvent.BUTTON1_MASK );
bot.mouseRelease( InputEvent.BUTTON1_MASK );
System.out.println( "Mouse clicked at: " + x + " : " + y );

This is how we can simply perform a mouse click using a program. The code below further enhances it by using a simple implementation of Thread to listen for the change and perform the click.

package com.myapp.utilities;
import java.awt.AWTException; import java.awt.Robot; import java.awt.event.InputEvent;
public class MouseClickUtility implements Runnable {
public static boolean active = false;
public static int interval = 500;
@Override
public void run() {
try {
while( true ) { if( active ) {
int mouseY = MouseInfo.getPointerInfo().getLocation().y;
int mouseX = MouseInfo.getPointerInfo().getLocation().x;
System.out.println( "Mouse positioned at: " + mouseY + " : " + mouseX );
Robot bot = new Robot();
bot.mouseMove( mouseY, mouseX ); bot.mousePress( InputEvent.BUTTON1_MASK ); bot.mouseRelease( InputEvent.BUTTON1_MASK );
System.out.println( "Mouse clicked at: " + x + " : " + y ); }
Thread.sleep( interval );
}
}
catch( InterruptedException e ) {
e.printStackTrace(); }
catch( AWTException e ) { e.printStackTrace(); } } }

Share this blog:

Profile picture for user bhagwatchouhan
bhagwatchouhan