KeyBoard Functions Using Robots Class In Selenium Webdriver


By using this we can test the keyboard events of an application.This post helps you to do it.

Note :We can also use Actions class and also Javascript.

Robot Functions

InputEvent.BUTTON1_MASK // Left button
InputEvent.BUTTON2_MASK // Middle button
InputEvent.BUTTON3_MASK // Right button

Middle click | Press & Release
Robot r = new Robot();
r.mousePress(InputEvent.BUTTON2_MASK);
r.mouseRelease(InputEvent.BUTTON2_MASK);

Right click | Press & Release
r.mousePress(InputEvent.BUTTON3_MASK);
r.mouseRelease(InputEvent.BUTTON3_MASK);

Scroll Mouse
r.mouseWheel(7);

Pixel Color | RBG
System.out.println(r.getPixelColor(923, 87));
OUTPUT|
java.awt.Color[r=142,g=209,b=224]

Get Current Mouse position [location]
System.out.println(MouseInfo.getPointerInfo().getLocation());
OUTPUT|
java.awt.Point[x=735,y=633]

Get Screen Resolution | Dimension
System.out.println(Toolkit.getDefaultToolkit().getScreenSize());
OUTPUT|
java.awt.Dimension[width=1920,height=1080]

Screen Capture
java.awt.Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
Robot r = new Robot();
BufferedImage img = r.createScreenCapture(new Rectangle(size));
File path = new File(“C://screen.jpg”);
ImageIO.write(img, “JPG”, path);
or|
Robot r = new Robot();
BufferedImage img = r.createScreenCapture(new Rectangle(0, 0, 100, 100));
File path = new File(“C://screen.jpg”);
ImageIO.write(img, “JPG”, path);

Enter/Type Text
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.lang.reflect.Field;

Robot r = new Robot();
driver.findElement(By.id(“Value”)).click();
typeKeys(“Prashanth Sams”, r);

public static void typeKeys(String str,Robot r)
{
for(int i=0;i<str.length();i++)
{
typeCharacter(r, ""+str.charAt(i));
}
}
public static void typeCharacter(Robot robot, String letter)
{
try
{
boolean upperCase = Character.isUpperCase( letter.charAt(0) );
String variableName = "VK_" + letter.toUpperCase();
Class clazz = KeyEvent.class;
Field field = clazz.getField( variableName );
int keyCode = field.getInt(null);

robot.delay(1000);

if (upperCase) robot.keyPress( KeyEvent.VK_SHIFT );

robot.keyPress( keyCode );
robot.keyRelease( keyCode );

if (upperCase) robot.keyRelease( KeyEvent.VK_SHIFT );
}
catch(Exception e)
{
System.out.println(e);
}
}

Keyboard Actions
r.keyPress(KeyEvent.VK_ENTER); // Press Enter Key

Find all/rest of the Java Robot keyboard actions here
Refer| Robot

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s