如何使 Java.awt.Robot 类型的 unicode 字符?(是否可以?) [英] How to make the Java.awt.Robot type unicode characters? (Is it possible?)

查看:21
本文介绍了如何使 Java.awt.Robot 类型的 unicode 字符?(是否可以?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个用户提供的可能包含 unicode 字符的字符串,我们希望机器人输入该字符串.

We have a user provided string that may contain unicode characters, and we want the robot to type that string.

如何将字符串转换为机器人将使用的 keyCode?
你是怎么做到的,所以它也是 Java 版本独立的 (1.3 -> 1.6)?

How do you convert a string into keyCodes that the robot will use?
How do you do it so it is also java version independant (1.3 -> 1.6)?

我们为ascii"字符所做的工作是

What we have working for "ascii" chars is

//char c = nextChar();
//char c = 'a'; // this works, and so does 'A'
char c = 'á'; // this doesn't, and neither does 'Ă'
Robot robot = new Robot();
KeyStroke key = KeyStroke.getKeyStroke("pressed " + Character.toUpperCase(c) );
if( null != key ) {
  // should only have to worry about case with standard characters
  if (Character.isUpperCase(c))
  {
    robot.keyPress(KeyEvent.VK_SHIFT);
  }

  robot.keyPress(key.getKeyCode());
  robot.keyRelease(key.getKeyCode());

  if (Character.isUpperCase(c))
  {
    robot.keyRelease(KeyEvent.VK_SHIFT);
  }
}

推荐答案

基于 javamonkey79 的代码,我创建了以下应该适用于所有 Unicode 值的代码片段...

Based on javamonkey79's code I've created the following snippet which should work for all Unicode values...

public static void pressUnicode(Robot r, int key_code)
{
    r.keyPress(KeyEvent.VK_ALT);

    for(int i = 3; i >= 0; --i)
    {
        // extracts a single decade of the key-code and adds
        // an offset to get the required VK_NUMPAD key-code
        int numpad_kc = key_code / (int) (Math.pow(10, i)) % 10 + KeyEvent.VK_NUMPAD0;

        r.keyPress(numpad_kc);
        r.keyRelease(numpad_kc);
    }

    r.keyRelease(KeyEvent.VK_ALT);
}

这会自动遍历 unicode 键码的每个十年,将其映射到相应的 VK_NUMPAD 等效项,并相应地按下/释放键.

This automatically goes through each decade of the unicode key-code, maps it to the corresponding VK_NUMPAD equivalent and presses/releases the keys accordingly.

这篇关于如何使 Java.awt.Robot 类型的 unicode 字符?(是否可以?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆