Simulate Copy Paste action using Java Robot and Clipboard class

Sometimes we need to simulate keyboard actions without disturbing the present cursor focus.For Example:
Testing with Selenium WebDriver-browseWhen we click on any file upload button a file upload windows opens up , where we need to give the path to the file we want to upload.
There are ways in Selenium WebDriver where we try to input the path to the file to the button element, but in some cases it does not work . So we can paste the path in the window and simulate enter key event without disturbing the present focus by the following way -Also If we are using Robot class anywhere to enter String, instead of checking each byte of String one by one and simulate key according to that – we can directly paste the whole String at once. This can be done using Clipboard class — Simulates copy paste action.
//Create instance of Robot class
   Robot robot = new Robot();

//Create instance of Clipboard class

   Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

//Set the String to Enter

  StringSelection stringSelection = new StringSelection(“String to enter”);

//Copy the String to Clipboard

  clipboard.setContents(stringSelection, null);

//Use Robot class instance to simulate CTRL+C and CTRL+V key events :


//Simulate Enter key event

Basically this is quite helpful to handle window events those can not be handled by Selenium WebDriver.

  • Ramesh P

    this is not working while we minimize the webdriver browser and work on other applications
    any solution for that?