我最近一直在搞乱机器人类,并想尝试在搜索栏中远程键入搜索,但我似乎无法输出整个字符串。 只有最后一个字母最终会在搜索栏中输入。文本的其余部分最终会打印在终端中,我在那里运行代码。
首先将鼠标移到选择框上方。
我点击鼠标两次(一次使safari成为活动窗口,一次激活吧)
然后我为我输入了类型函数类型。它使用按键和键释放方法。
有人知道如何在搜索栏中输入整个字符串吗?
另外,我在Convert String to KeyEvents的stackoverflow帖子中赞扬了Sensei_Shoh 他的代码从第38行到结尾。 感谢。
import java.awt.*;
import java.awt.event.*;
import static java.awt.event.KeyEvent.*;
import java.util.*;
import java.awt.datatransfer.*;
import static java.awt.AWTKeyStroke.getAWTKeyStroke;
import static java.awt.event.InputEvent.SHIFT_DOWN_MASK;
public class myBot
{
public static Robot robot;
public static void main(String[] args) throws AWTException
{
Scanner in = new Scanner(System.in);
robot = new Robot();
//Move to search bar
robot.delay(500);
robot.mouseMove(600,140);
//Activate search bar
robot.mousePress( InputEvent.BUTTON1_MASK );
robot.mouseRelease( InputEvent.BUTTON1_MASK );
robot.delay(100);
robot.mousePress( InputEvent.BUTTON1_MASK );
robot.mouseRelease( InputEvent.BUTTON1_MASK );
robot.delay(1000);
//Type in search bar;
//YOUR STRING \/
String input = "ipad pro";
for(int i=0; i<input.length(); i++)
{
type(input.substring(i, i+1));
}
}
private static AWTKeyStroke getKeyStroke(char c) {
String upper = "`~'\"!@#$%^&*()_+{}|:<>?";
String lower = "`~'\"1234567890-=[]\\;,./";
int index = upper.indexOf(c);
if (index != -1) {
int keyCode;
boolean shift = false;
switch (c) {
case '~':
shift = true;
case '`':
keyCode = KeyEvent.VK_BACK_QUOTE;
break;
case '\"':
shift = true;
case '\'':
keyCode = KeyEvent.VK_QUOTE;
break;
default:
keyCode = (int) Character.toUpperCase(lower.charAt(index));
shift = true;
}
return getAWTKeyStroke(keyCode, shift ? SHIFT_DOWN_MASK : 0);
}
return getAWTKeyStroke((int) Character.toUpperCase(c), 0);
}
public static void type(CharSequence chars) {
type(chars, 0);
}
public static void type(CharSequence chars, int ms) {
ms = ms > 0 ? ms : 0;
for (int i = 0, len = chars.length(); i < len; i++) {
char c = chars.charAt(i);
AWTKeyStroke keyStroke = getKeyStroke(c);
int keyCode = keyStroke.getKeyCode();
boolean shift = Character.isUpperCase(c) || keyStroke.getModifiers() == (SHIFT_DOWN_MASK + 1);
if (shift) {
robot.keyPress(KeyEvent.VK_SHIFT);
}
robot.keyPress(keyCode);
robot.keyRelease(keyCode);
if (shift) {
robot.keyRelease(KeyEvent.VK_SHIFT);
}
if (ms > 0) {
robot.delay(ms);
}
}
}
}