使用 java.awt.Robot 键入字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29665534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:24:02  来源:igfitidea点击:

Type a String using java.awt.Robot

javaswingawtrobot

提问by

I already know how to use java.awt.Robotto type a single character using keyPress, as seen below. How can I simply enter a wholepre-defined Stringvalue at onceinto a textbox?

我已经知道如何使用java.awt.Robot键入单个字符keyPress,如下所示。我怎么能简单地输入一个预先定义的String立刻变成一个文本框?

robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);  
// instead, enter String x = "111"

采纳答案by Eng.Fouad

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);

回答by MadProgrammer

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

现在你可以复制粘贴三遍,但我只是把它放在一个循环中

回答by Luffy

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

您可以在字符串中输入值,然后您可以按照 Eng.Fouad 的说明使用该字符串。但是使用起来没什么乐趣,你可以试试这个

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.

也可以使用 Thread.sleep 来缓慢输入数据位。

回答by Adrian Kapuscinski

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)

我想我已经实现了更好的灵魂,也许有人发现它有用(主要方法是从枚举 KeyCode 中读取所有值,而不是将其放入 HashMap 并稍后使用它来查找 int 键代码)

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

最后你可以像这样使用它(对于单个字符)robot.keyPress(charToKey('a').getKeyCode());如果你想按下一个大写字母,你必须同时按下和释放 shift 键

回答by geri

Since Java 7 you can also use KeyEvent.getExtendedKeyCodeForChar(c). An example for lower case only could be:

从 Java 7 开始,您还可以使用 KeyEvent.getExtendedKeyCodeForChar(c)。仅小写的示例可能是:

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);
    }
}

回答by Abhilash Messi

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.

看到它完美运行,真是太棒了!尽管它不适用于无法通过 unicode 跟踪的特殊字符,例如 |,!... 等。

回答by Jagdish Odedra

    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);

}