[英]How to make the Java.awt.Robot type unicode characters? (Is it possible?)
我們有一個用戶提供的可能包含 unicode 字符的字符串,我們希望機器人輸入該字符串。
如何將字符串轉換為機器人將使用的 keyCode?
你是怎么做的,所以它也是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 等效項,並相應地按下/釋放鍵。
KeyEvent 類沒有直接映射 JRE 1.5 中的許多 unicode 類。 如果您在 Windows 機器上運行它,您可能需要編寫一個自定義處理程序,執行如下操作:
Robot robot = new Robot();
char curChar = 'Ã';
// -- isUnicode( char ) should be pretty easy to figure out
if ( isUnicode( curChar ) ) {
// -- this is an example, exact key combinations will vary
robot.keyPress( KeyEvent.VK_ALT );
robot.keyPress( KeyEvent.VK_NUMBER_SIGN );
robot.keyRelease( KeyEvent.VK_NUMBER_SIGN );
// -- have to apply some logic to know what sequence
robot.keyPress( KeyEvent.VK_0 );
robot.keyRelease( KeyEvent.VK_0 );
robot.keyPress( KeyEvent.VK_1 );
robot.keyRelease( KeyEvent.VK_1 );
robot.keyPress( KeyEvent.VK_9 );
robot.keyRelease( KeyEvent.VK_9 );
robot.keyPress( KeyEvent.VK_5 );
robot.keyRelease( KeyEvent.VK_5 );
robot.keyRelease( KeyEvent.VK_ALT );
}
例如,弄清楚它們的鍵組合是什么,然后將它們映射到某種對象(可能是 HashMap?)以供以后查找和執行。
希望這可以幫助 :)
我覺得這有點晚了但是...
Robot robot = new Robot();
robot.keyPress( KeyEvent.VK_DEAD_ACUTE);
robot.keyPress( KeyEvent.VK_A );
robot.keyRelease( KeyEvent.VK_A );
robot.keyRelease( KeyEvent.VK_DEAD_ACUTE );
只需輸入“á”
這是有效的,我在筆記本電腦中嘗試相同,看起來不像是幫助我使用java機器人鍵入unicode字符。 為此更多的光。
我在解決simulare問題時找到的最好方法
import java.awt.AWTException;
import java.awt.Robot;
public class MyRobot {
public static void typeString(String s)
{
try {
Robot robik = new Robot();
byte[] bytes = s.getBytes();
for (byte b : bytes)
{
int code = b;
// keycode only handles [A-Z] (which is ASCII decimal [65-90])
if (code > 96 && code < 123) code = code - 32;
robik.delay(40);
robik.keyPress(code);
robik.keyRelease(code);
}
} catch (AWTException e){
}
}
}
http://www.devdaily.com/java/java-robot-class-example-mouse-keystroke \\
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.