我们有一个用户提供的字符串,其中可能包含 unicode 字符,我们希望机器人键入该字符串。
如何将字符串转换为机器人将使用的 keyCodes?
你是怎么做到它也是 Java 版本独立的(1.3 -> 1.6)?
我们为“ascii”字符工作的是
//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 值...
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 等效项并相应地按下/释放键。
关于java - 如何制作 Java.awt.Robot 类型的 unicode 字符? (可能吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/397113/