我们有一个用户提供的字符串,其中可能包含 unicode 字符,并且我们希望机器人键入该字符串。
如何将字符串转换为机器人将使用的键码?
你如何做到这一点,使它也独立于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 等效值,并相应地按下/释放按键。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)