I've been trying to use Robot from awt, to input some text on a app. The problem it's that i can't make it type any letters like ê, à or á.
I have tried doing this such printing ^e for example but even that works, it just dosen't print anything for VK_CIRCUMFLEX
Not sure if it matters but i'm testing on a Mac.
Any help would be well come.
You can use the clipboard combined with CTRL/COMMAND+V to do the job for you. The code below works on Windows at least (Mac key combo probably requires a different sequence to do a paste).
public static void main(String[] args) throws AWTException {
String osName = System.getProperty("os.name");
boolean isOSX = osName.startsWith("Mac OS X");
boolean isWin = osName.startsWith("Windows");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection str = new StringSelection("Héllõ Wörld");
clipboard.setContents(str, str);
Robot robot = new Robot();
if (isMac) {
// ⌘-V on Mac
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_META);
} else if (isWin) {
// Ctrl-V on Win
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
} else {
throw new AssertionError("Not tested on "+osName);
}
}
Related
I tried implementing Robot class in my Selenium Test cases written using Java. I am getting a strange issue there. So when I am trying to run those test cases on my local machine (Windows 10 Enterprise Edition) and monitoring it's working fine and the file is getting uploaded. But when I am trying to run those in a remote server (Windows Server 2012) and monitoring those it's again working fine but when I am leaving those test cases for the entire night to run I found that the File Explorer dialogue box is opening but it's never getting close. It might be that the file path is not getting pasted and the Enter (Ok) button is not getting clicked.
public void uploadFile(String path) {
String abspath = _getAbsolutePath(path);
StringSelection stringSelection = new StringSelection(abspath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
Robot robot = null;
try {
// native key strokes for CTRL, V and ENTER keys
robot = new Robot();
robot.setAutoDelay(5000);
robot.keyPress(KeyEvent.VK_CONTROL); // Press Ctrl
robot.keyPress(KeyEvent.VK_V); // Pres V
robot.keyRelease(KeyEvent.VK_V); // Release Ctrl
robot.keyRelease(KeyEvent.VK_CONTROL); // Release V
robot.setAutoDelay(5000);
robot.keyPress(KeyEvent.VK_ENTER); // Press Enter
robot.keyRelease(KeyEvent.VK_ENTER); // Release Enter
} catch (Exception exp) {
exp.printStackTrace();
}
}
I am trying to copy words from anywhere (like MS word, pdf, not from any java component) to clip board when I double click on it. Therefore, I use awt.Robot to copy that selected word to clip board after double click on it. After copy, the word will return. Therefore, I use two method copy_From_Original and copy_From_ClipBoard.
The problem is when I copy word, it will show the previous word that clipboard content not the current copied one.
If there are, another ways to do this process feel free to say it.
Thanks. Sorry for my bad English.
public class copyWord {
public static String copy_From_Original() {
try {
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_CONTROL);
} catch (AWTException ex) {
Logger.getLogger(copyWord.class.getName()).log(Level.SEVERE, null, ex);
}
String word = copy_From_ClipBoard();
return word;
}
private static String copy_From_ClipBoard() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Clipboard clipboard = toolkit.getSystemClipboard();
try {
String result = (String) clipboard.getData(DataFlavor.stringFlavor);
return result;
} catch (Exception e) {
System.out.println("ERROR");
return null;
}
} }
Do not use Robot for this. You haven’t said what type of component contains the double-clicked text, but if it’s a JTextField or JTextArea or any other subclass of JTextComponent, you can simply call copy().
If it’s an AWT TextField or TextArea, you can use place the selection on the clipboard yourself:
String text = textField.getSelectedText();
Clipboard clipboard = textField.getToolkit().getSystemClipboard();
clipboard.setContents(new StringSelection(text), null);
OK, so I am trying to export a file using Selenium. My browser is IE. When I click on the export button a native windows dialogue box comes up.
Image of the pop up
I have to click on the Save button. For this I tried using AutoIT but its not working.
exportbutton.click();
Thread.sleep(2000);
driver.switchTo().activeElement();
AutoItX x = new AutoItX();
x.winActivate("window name");
x.winWaitActive("window name");
x.controlClick("window name", "", "[CLASS:Button; INSTANCE:2]");
This did not work. So I decided to use Robot class and perform the keyboard clicks Atl + S, as this will also enable the browser to Save the file. That did not work either.
try
{
Robot robot = new Robot();
robot.setAutoDelay(250);
robot.keyPress(KeyEvent.VK_ALT);
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
}
catch (AWTException e)
{
e.printStackTrace();
}
There is some problem with the web driver I suppose because I tried printing a line after exportbutton.click() and it did not get printed either.
I am new so I can't understand the problem. Please help me out.
So, the problem was that the cursor gets stuck sometimes when you call the click() function. So as a solution I used the Robot class to move my cursor and click on the export button and then I used Robot class to press Alt+S, which is a keyboard shortcut to save a file in IE.
To click on the button I used
try
{
Robot robot = new Robot();
Thread.sleep(2000);
robot.mouseMove(coordinates.getX()+100,coordinates.getY()-400);
Thread.sleep(2000);
robot.mousePress( InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
catch (AWTException e)
{
e.printStackTrace();
}
To get the coordinates in the above snippet I used the following line
Point coordinates = driver.findElement(By.id("id")).getLocation();
System.out.println("Co-ordinates"+coordinates);
And to press Alt+S I used the following code
try
{
Robot robot = new Robot();
robot.setAutoDelay(250);
robot.keyPress(KeyEvent.VK_ALT);
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
}
catch (AWTException e)
{
e.printStackTrace();
}
I had the same problem. I came to realization that
button.click()
does not work very well in this case (with IE driver). So instead of clicking the button I tried this:
robot = new Robot();
button.sendKeys("""");
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
This just gives focus on button and 'presses' it by hitting enter.
Sorry, I wrote approach how to upload the file. If you want to download - use the same approach, but use another buttons: Instead buttons Cntrl + V you can use button Tab to find control of Save/Save as and then Press Enter. Before it, you can paste String with file path ( directory where you want to upload your file).
Auto IT is not required to handle this. just use the below code and it works fine.
If we give element.click on the element, control stops there and hence we use element.sendkeys("") and robot.keyPress(KeyEvent.VK_ENTER);
Below is the complete code:
Robot robot = new Robot();
//get the focus on the element..don't use click since it stalls the driver
element.sendKeys("");
//simulate pressing enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
//wait for the modal dialog to open
Thread.sleep(2000);
//press s key to save
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_N);
robot.keyRelease(KeyEvent.VK_N);
robot.keyRelease(KeyEvent.VK_ALT);
Thread.sleep(2000);
//press enter to save the file with default name and in default location
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
I used AutoIt and it works in windows 10. Refer to the below AutoIt script :
Sleep(9000);
Local $hIE = WinGetHandle("[Class:IEFrame]");
Local $hCtrl = ControlGetHandle($hIE, "", "[ClassNN:DirectUIHWND1]");
If WinExists($hIE,"") Then
WinActivate($hIE,"");
ControlSend($hIE ,"",$hCtrl,"{F6}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{ENTER}");
EndIf
Sleep(5000);
If WinExists($hIE,"") Then
WinActivate($hIE,"");
ControlSend($hIE ,"",$hCtrl,"{F6}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{ENTER}");
EndIf
Sleep(5000);
It clicks the save button and also closes the next alert.
Please adjust Sleep() accordingly.
This is a hack by Dave Haefner. If you don't care if a file was downloaded or not and you want to confirm only that a file can be downloaded, you can use an HTTP request. Instead of downloading the file you'll receive the header information for the file which contains things like the content type and length. With this information, you can confirm the file is you expect.
String link = driver.findElement(By.cssSelector("download-link-element")).getAttribute("href");
HttpClient httpClient = HttpClientBuilder.create().build();
HttpHead request = new HttpHead(link);
HttpResponse response = httpClient.execute(request);
String contentType = response.getFirstHeader("Content-Type").getValue();
int contentLength = Integer.parseInt(response.getFirstHeader("Content-Length").getValue());
assertThat(contentType, is("application/octet-stream"));
assertThat(contentLength, is(not(0)));
I already know how to use java.awt.Robot to type a single character using keyPress, as seen below. How can I simply enter a whole pre-defined String value at once into a textbox?
robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);
// instead, enter String x = "111"
Common solution is to use the clipboard:
String text = "Hello World";
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
Since Java 7 you can also use KeyEvent.getExtendedKeyCodeForChar(c). An example for lower case only could be:
void sendKeys(Robot robot, String keys) {
for (char c : keys.toCharArray()) {
int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
if (KeyEvent.CHAR_UNDEFINED == keyCode) {
throw new RuntimeException(
"Key code not found for character '" + c + "'");
}
robot.keyPress(keyCode);
robot.delay(100);
robot.keyRelease(keyCode);
robot.delay(100);
}
}
You need to "type" the character, which is a press AND release action...
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_1);
Now you could just copy and paste it three times, but I'd just put it in a loop
You can enter value in a string and then you can use that string as explained by Eng.Fouad. But there is no fun in using it, you can give a try to this
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_H);
robot.keyRelease(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_E);
robot.keyRelease(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_O);
and you can also use Thread.sleep so that it can enter data bit slowly.
This doesn't type the entire "string" but helps to type whatever you want other than one character at a time.
Runtime.getRuntime().exec("notepad.exe");//or anywhere you want.
Thread.sleep(5000);//not required though gives a good feel.
Robot r=new Robot();
String a="Hi My name is Whatever you want to say.";
char c;
int d=a.length(),e=0,f=0;
while(e<=d)
{
c=a.charAt(e);
f=(int) c; //converts character to Unicode.
r.keyPress(KeyEvent.getExtendedKeyCodeForChar(f));
e++;
Thread.sleep(150);
}
see it works perfectly and it's awesome!
Though it doesn't work for special characters which cannot be traced by unicode like |,!...etc.
I think I've implemented better soultion, maybe someone found it usefull (the main approach is to read all values from enum KeyCode and than to put it into a HashMap and use it later to find a int key code)
public class KeysMapper {
private static HashMap<Character, Integer> charMap = new HashMap<Character, Integer>();
static {
for (KeyCode keyCode : KeyCode.values()) {
if (keyCode.impl_getCode() >= 65 && keyCode.impl_getCode() <= 90){
charMap.put(keyCode.getName().toLowerCase().toCharArray()[0], keyCode.impl_getCode());
}
else{
charMap.put(keyCode.getName().toLowerCase().toCharArray()[0], keyCode.impl_getCode());
}
}
}
public static Key charToKey(char c){
if(c>=65 && c<=90){
return new Key(charMap.get(c), true);
} else {
return new Key(charMap.get(c), false);
}
}
public static List<Key> stringToKeys(String text){
List<Key> keys = new ArrayList<Key>();
for (char c : text.toCharArray()) {
keys.add(charToKey(c));
}
return keys;
}
I created also a key class to know whether to type an uppercase or lowercase char:
public class Key {
int keyCode;
boolean uppercase;
//getters setter constructors}
and finally you can use it like that (for single character) robot.keyPress(charToKey('a').getKeyCode());
If you want to press an uppercase you have to press and release with shift key simultaneously
StringSelection path = new StringSelection("path of your document ");
// create an object to desktop
Toolkit tol = Toolkit.getDefaultToolkit();
// get control of mouse cursor
Clipboard c = tol.getSystemClipboard();
// copy the path into mouse
c.setContents(path, null);
// create a object of robot class
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_V);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_V);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
}
How to send capital text to a text box using Robot class and Selenium WebDriver.
You need to do two things to:
1- First to get focus to the textfield, where you want to enter the value, like this:
driver.findElement(By.xpath("//xpath of the element")).sendKeys("")// id or class can be used as locators too.
2- Then use 'Robot class' to send values to the field (using CAPSLOCK or SHIFT keys for changing the letters to uppercase).
Try this code. It works for sending "HELLO" (all caps) in Google.com's search field using "CAPSLOCK":
//Navigating to the site
driver.get("http://www.google.com");
//To get the focus on the searchbox (NOT ENTERING ANYTHING)
driver.findElement(By.id("gbqfq")).sendKeys("");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
robot.keyPress(KeyEvent.VK_H);
robot.keyRelease(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_E);
robot.keyRelease(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
OR you can try using "SHIFT" as below:
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_H);
robot.keyRelease(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_E);
robot.keyRelease(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_SHIFT);
You can send caps text to a text box using Robot class in following manner.
Below i am sending String OK using Robot class
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyPress(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyPress(KeyEvent.VK_K);
robot.keyRelease(KeyEvent.VK_K);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
It can be done by using "Caps Lock" or "Shift" key, that code has been mentioned here in another answer by Subh.
You can also do it by using StringSelection in Java. The code is as below:
//First of all declare the method setClipboardData as below:
public void setClipboardData(String string) {
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
//Call the method setClipboardData and write other Robot code:
driver.get("https://www.google.com/");
driver.findElement(By.id("lst-ib")).clear();
driver.findElement(By.id("lst-ib")).sendKeys("");
Robot robot = new Robot();
setClipboardData("ALL CAPS");
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);