【问题标题】:How to send a string which contains caps and small case character as well special character using java.awt.Robot?如何使用 java.awt.Robot 发送包含大写字母和小写字符以及特殊字符的字符串?
【发布时间】:2019-10-03 14:06:27
【问题描述】:

假设我想发送下面的字符串

String 1 : cd /srcdir/data/PTcpGateway

String 2 : vi am1py_packets_PS.config

我不想一个一个地发送一个字符,而是想一次性发送整个字符串。可以使用 Java Robot 吗?

我尝试关注this 的帖子,但它对我不起作用。

【问题讨论】:

  • 当您关注其他帖子时,什么对您不起作用?你得到了什么错误?请提供您尝试过的代码以及任何错误/结果。
  • “发送”是什么意思?如果您已经知道 String 是什么,您为什么认为还需要使用 Robot?
  • @camickr 我想在腻子自动化中发送这样的字符串作为命令
  • 我不知道什么是“腻子自动化”。在任何情况下,Robot 类一次只能发送一个字符。因此,您需要创建一个方法来构建字符串并让机器人一次从字符串中发送 1 个字符。就像在键盘上键入时,一次只能键入一个字符。机器人没有复制/粘贴功能。

标签: java swing awtrobot


【解决方案1】:

对于腻子自动化,我相信可以工作的代码应该在下面,考虑到它在大型机应用程序界面上对我有用。它或多或少类似于预计的解决方案。

片段 1:-

public static void typeAction (String text, int waitAfterKeyPressRelease) throws InterruptedException, AWTException  {

    // Performs Copy Paste of chain of keys ... i.e. word ( including special chars )
    StringSelection stringSelection = new StringSelection(text);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, stringSelection);

    Thread.sleep(2000);
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);

}

片段 2:

public static void typeAction (char[] text, int waitAfterKeyPressRelease) throws InterruptedException, AWTException  {

     for (char c : text) {            
         int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
            if (KeyEvent.CHAR_UNDEFINED == keyCode  || keyCode == KeyEvent.VK_UNDEFINED )
                throw new RuntimeException("Key code not found for character '" + c + "'");
            robot.keyPress(keyCode);
                robot.delay(10);
            robot.keyRelease(keyCode);
                robot.delay(10);
     }
}

片段 3:

public static void typeAction( int key, int waitAfterKeyPressRelease) {


    try{
        robot = new Robot();
            robot.keyPress(key);
                if(waitAfterKeyPressRelease>0)  Thread.sleep(waitAfterKeyPressRelease);
            robot.keyRelease(key);
                if(waitAfterKeyPressRelease>0)  Thread.sleep(waitAfterKeyPressRelease);
    }

    catch ( AWTException awt)   {   awt.printStackTrace();  }
    catch (InterruptedException Int)    {   Int.printStackTrace();  }

}

【讨论】:

    猜你喜欢
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2022-06-17
    相关资源
    最近更新 更多