Java 将字符串转换为 KeyEvent
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1248510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert String to KeyEvents
提问by Martin Trigaux
I want to convert a String into KeyEvent to do something like this :
我想将一个字符串转换为 KeyEvent 来做这样的事情:
writeKeyboard(myBot,"abcd");
public void writeKeyboard(Robot bot, String st){
char[] arr = arr.toCharArray();
int i = arr.length();
int j = 0;
int keycode;
while (j<i) {
keycode = arr[j].something;
bot.keyPress(keycode);
bot.keyRelease(keycode);
j++;
}
}
采纳答案by Adam Paynter
I'm basically using a glorified switch
statement. Simple and fast:
我基本上是在使用一个美化的switch
声明。简单快速:
import static java.awt.event.KeyEvent.*;
public class Keyboard {
private Robot robot;
public static void main(String... args) throws Exception {
Keyboard keyboard = new Keyboard();
keyboard.type("Hello there, how are you?");
}
public Keyboard() throws AWTException {
this.robot = new Robot();
}
public Keyboard(Robot robot) {
this.robot = robot;
}
public void type(CharSequence characters) {
int length = characters.length();
for (int i = 0; i < length; i++) {
char character = characters.charAt(i);
type(character);
}
}
public void type(char character) {
switch (character) {
case 'a': doType(VK_A); break;
case 'b': doType(VK_B); break;
case 'c': doType(VK_C); break;
case 'd': doType(VK_D); break;
case 'e': doType(VK_E); break;
case 'f': doType(VK_F); break;
case 'g': doType(VK_G); break;
case 'h': doType(VK_H); break;
case 'i': doType(VK_I); break;
case 'j': doType(VK_J); break;
case 'k': doType(VK_K); break;
case 'l': doType(VK_L); break;
case 'm': doType(VK_M); break;
case 'n': doType(VK_N); break;
case 'o': doType(VK_O); break;
case 'p': doType(VK_P); break;
case 'q': doType(VK_Q); break;
case 'r': doType(VK_R); break;
case 's': doType(VK_S); break;
case 't': doType(VK_T); break;
case 'u': doType(VK_U); break;
case 'v': doType(VK_V); break;
case 'w': doType(VK_W); break;
case 'x': doType(VK_X); break;
case 'y': doType(VK_Y); break;
case 'z': doType(VK_Z); break;
case 'A': doType(VK_SHIFT, VK_A); break;
case 'B': doType(VK_SHIFT, VK_B); break;
case 'C': doType(VK_SHIFT, VK_C); break;
case 'D': doType(VK_SHIFT, VK_D); break;
case 'E': doType(VK_SHIFT, VK_E); break;
case 'F': doType(VK_SHIFT, VK_F); break;
case 'G': doType(VK_SHIFT, VK_G); break;
case 'H': doType(VK_SHIFT, VK_H); break;
case 'I': doType(VK_SHIFT, VK_I); break;
case 'J': doType(VK_SHIFT, VK_J); break;
case 'K': doType(VK_SHIFT, VK_K); break;
case 'L': doType(VK_SHIFT, VK_L); break;
case 'M': doType(VK_SHIFT, VK_M); break;
case 'N': doType(VK_SHIFT, VK_N); break;
case 'O': doType(VK_SHIFT, VK_O); break;
case 'P': doType(VK_SHIFT, VK_P); break;
case 'Q': doType(VK_SHIFT, VK_Q); break;
case 'R': doType(VK_SHIFT, VK_R); break;
case 'S': doType(VK_SHIFT, VK_S); break;
case 'T': doType(VK_SHIFT, VK_T); break;
case 'U': doType(VK_SHIFT, VK_U); break;
case 'V': doType(VK_SHIFT, VK_V); break;
case 'W': doType(VK_SHIFT, VK_W); break;
case 'X': doType(VK_SHIFT, VK_X); break;
case 'Y': doType(VK_SHIFT, VK_Y); break;
case 'Z': doType(VK_SHIFT, VK_Z); break;
case '`': doType(VK_BACK_QUOTE); break;
case '0': doType(VK_0); break;
case '1': doType(VK_1); break;
case '2': doType(VK_2); break;
case '3': doType(VK_3); break;
case '4': doType(VK_4); break;
case '5': doType(VK_5); break;
case '6': doType(VK_6); break;
case '7': doType(VK_7); break;
case '8': doType(VK_8); break;
case '9': doType(VK_9); break;
case '-': doType(VK_MINUS); break;
case '=': doType(VK_EQUALS); break;
case '~': doType(VK_SHIFT, VK_BACK_QUOTE); break;
case '!': doType(VK_EXCLAMATION_MARK); break;
case '@': doType(VK_AT); break;
case '#': doType(VK_NUMBER_SIGN); break;
case '$': doType(VK_DOLLAR); break;
case '%': doType(VK_SHIFT, VK_5); break;
case '^': doType(VK_CIRCUMFLEX); break;
case '&': doType(VK_AMPERSAND); break;
case '*': doType(VK_ASTERISK); break;
case '(': doType(VK_LEFT_PARENTHESIS); break;
case ')': doType(VK_RIGHT_PARENTHESIS); break;
case '_': doType(VK_UNDERSCORE); break;
case '+': doType(VK_PLUS); break;
case '\t': doType(VK_TAB); break;
case '\n': doType(VK_ENTER); break;
case '[': doType(VK_OPEN_BRACKET); break;
case ']': doType(VK_CLOSE_BRACKET); break;
case '\': doType(VK_BACK_SLASH); break;
case '{': doType(VK_SHIFT, VK_OPEN_BRACKET); break;
case '}': doType(VK_SHIFT, VK_CLOSE_BRACKET); break;
case '|': doType(VK_SHIFT, VK_BACK_SLASH); break;
case ';': doType(VK_SEMICOLON); break;
case ':': doType(VK_COLON); break;
case '\'': doType(VK_QUOTE); break;
case '"': doType(VK_QUOTEDBL); break;
case ',': doType(VK_COMMA); break;
case '<': doType(VK_SHIFT, VK_COMMA); break;
case '.': doType(VK_PERIOD); break;
case '>': doType(VK_SHIFT, VK_PERIOD); break;
case '/': doType(VK_SLASH); break;
case '?': doType(VK_SHIFT, VK_SLASH); break;
case ' ': doType(VK_SPACE); break;
default:
throw new IllegalArgumentException("Cannot type character " + character);
}
}
private void doType(int... keyCodes) {
doType(keyCodes, 0, keyCodes.length);
}
private void doType(int[] keyCodes, int offset, int length) {
if (length == 0) {
return;
}
robot.keyPress(keyCodes[offset]);
doType(keyCodes, offset + 1, length - 1);
robot.keyRelease(keyCodes[offset]);
}
}
If you want some custom key typing, you can extend the class and override the type(char)
method. For example:
如果您想要一些自定义键输入,您可以扩展该类并覆盖该type(char)
方法。例如:
import static java.awt.event.KeyEvent.*;
public class WindowUnicodeKeyboard extends Keyboard {
private Robot robot;
public WindowUnicodeKeyboard(Robot robot) {
super(robot);
this.robot = robot;
}
@Override
public void type(char character) {
try {
super.type(character);
} catch (IllegalArgumentException e) {
String unicodeDigits = String.valueOf(Character.getCodePoint(character));
robot.keyPress(VK_ALT);
for (int i = 0; i < unicodeDigits.length(); i++) {
typeNumPad(Integer.parseInt(unicodeDigits.substring(i, i + 1)));
}
robot.keyRelease(VK_ALT);
}
}
private void typeNumPad(int digit) {
switch (digit) {
case 0: doType(VK_NUMPAD0); break;
case 1: doType(VK_NUMPAD1); break;
case 2: doType(VK_NUMPAD2); break;
case 3: doType(VK_NUMPAD3); break;
case 4: doType(VK_NUMPAD4); break;
case 5: doType(VK_NUMPAD5); break;
case 6: doType(VK_NUMPAD6); break;
case 7: doType(VK_NUMPAD7); break;
case 8: doType(VK_NUMPAD8); break;
case 9: doType(VK_NUMPAD9); break;
}
}
}
There is, of course, room for improvement, but you get the idea.
当然,还有改进的余地,但你明白了。
回答by Rich Seller
It's a bit of a Kludge, but you can use the Command patternto encapsulate the keystrokes for each character in the String, then get the Command for each character in turn and invoke the method. The advantage of this is that you only have to set up the map once. The disadvantage is it still involves a bunch of bolierplate:
有点Kludge,但是可以使用Command模式来封装String中每个字符的击键,然后依次获取每个字符的Command并调用该方法。这样做的好处是您只需设置一次地图。缺点是它仍然涉及一堆bolierplate:
public interface Command {
void pressKey(Robot bot);
}
//add a command to the map for each keystroke
commandMap.put("A", new Command() {
void pressKey(Robot bot) {
pressWithShift(KeyEvent.VK_A);
}
});
commandMap.put ("a", new Command() {
void pressKey (Robot bot) {
press (KeyEvent.VK_A);
}
});
commandMap.put("B", new Command() {
void pressKey(Robot bot) {
pressWithShift(KeyEvent.VK_B);
}
});
...
//loads more definitions here
//helper methods
private void pressWithShift (Robot bot, KeyEvent event) {
bot.keyPress (KeyEvent.VK_SHIFT);
press(bot, event);
bot.keyRelase(KeyEvent.VK_SHIFT);
}
private void press(Robot bot, KeyEvent event) {
bot.keyPress(event);
bot.keyRelease(event);
}
Then to use the Map:
然后使用地图:
for (int i = 0; i < st.length(); i++) {
String subString = st.substring(i, i + 1);
commandMap.get(subString).pressKey(bot);
}
回答by dfa
I'm basically using the Command patternas Rich Seller does in his answer, with two minor modifications for the brevity's sake:
我基本上使用命令模式,就像 Rich Seller 在他的回答中所做的那样,为了简洁起见,我做了两个小的修改:
- use of the Decoration patternfor reusing instances of a-z command
- use of reflection to remove KeyEvent.VK_???
- 使用装饰模式重用 az 命令的实例
- 使用反射删除 KeyEvent.VK_???
Command interface:
命令界面:
interface Command {
void pressKey(Robot robot);
}
and the decorator (for modification #1):
和装饰器(用于修改#1):
class ShiftCommand implements Command {
private final Command command;
public ShiftCommand(Command command) {
this.command = command;
}
public void pressKey(Robot robot) {
robot.keyPress(KeyEvent.VK_SHIFT);
command.pressKey(robot);
robot.keyRelease(KeyEvent.VK_SHIFT);
}
@Override
public String toString() {
return "SHIFT + " + command.toString();
}
}
using this helper (for modification #2):
使用此助手(用于修改 #2):
public static int getKeyEvent(Character c) {
Field f = KeyEvent.class.getField("VK_" + Character.toUpperCase(c));
f.setAccessible(true);
return (Integer) f.get(null);
}
BEWARE: I'm not handling exceptions here, this is left as exercise for you :))
当心:我不在这里处理异常,这留给你练习:))
then populating the command using a for loop:
然后使用 for 循环填充命令:
Map<Character, Command> commandMap = new HashMap<Character, Command>();
for (int i = 'a'; i <= 'z'; i++) {
final Character c = Character.valueOf((char) i);
Command pressKeyCommand = new Command() {
public void pressKey(Robot robot) {
int keyEventCode = getKeyEvent(c);
robot.keyPress(c);
robot.keyRelease(c);
}
@Override
public String toString() {
return String.format("%c", c);
}
};
// 'a' .. 'z'
commandMap.put(c, pressKeyCommand);
// 'A' .. 'Z' by decorating pressKeyCommand
commandMap.put(Character.toUpperCase(c), new ShiftCommand(pressKeyCommand));
}
TestCase
测试用例
String test = "aaaBBB";
for (int i = 0; i < test.length(); i++) {
System.out.println(commandMap.get(test.charAt(i)));
}
as expected this outputs:
正如预期的那样输出:
a a a SHIFT + b SHIFT + b SHIFT + b
回答by Martin Trigaux
I don't know the commandmap method but looks good, I'll have a look.
我不知道commandmap方法,但看起来不错,我去看看。
Finally I discover that the keycode for a to z is 65 to 90. So
最后我发现 a 到 z 的键码是 65 到 90。所以
private void write(Robot bot, String st) {
char[] arr = st.toCharArray();
int i = arr.length;
int j = 0;
while (j<i) {
int kcode = (int) arr[j] - 32;
bot.keyPress(kcode);
bot.keyRelease(kcode);
j++;
}
}
It just works for lowercase letters (you can easily correct it with a simple test for uppercase).
它只适用于小写字母(您可以通过简单的大写测试轻松纠正它)。
For what I was looking for it works perfectly :-)
对于我正在寻找的东西,它非常有效:-)
回答by Demiurg
Your code will work as long as you are using alpha numeric characters only, it will not work for characters like ":". SmartRobotclass will handle this.
只要您只使用字母数字字符,您的代码就可以工作,它不适用于像“:”这样的字符。SmartRobot类将处理此问题。
回答by trevorism
import java.awt.Robot;
import java.awt.event.KeyEvent;
/**
* @author Trevor
* Handles alpha numerics and common punctuation
*/
public class RobotKeyboard{
private Robot robot;
public RobotKeyboard(Robot robot){
this.robot = robot;
}
public void typeMessage(String message){
for (int i = 0; i < message.length(); i++){
handleRepeatCharacter(message, i);
type(message.charAt(i));
}
}
private void handleRepeatCharacter(String message, int i){
if(i == 0)
return;
//The robot won't type the same letter twice unless we release a key.
if(message.charAt(i) == message.charAt(i-1)){
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_SHIFT);
}
}
private void type(char character){
handleSpecialCharacter(character);
if (Character.isLowerCase(character)){
typeCharacter(Character.toUpperCase(character));
}
if (Character.isUpperCase(character)){
typeShiftCharacter(character);
}
if (Character.isDigit(character)){
typeCharacter(character);
}
}
private void handleSpecialCharacter(char character){
if (character == ' ')
typeCharacter(KeyEvent.VK_SPACE);
if (character == '.')
typeCharacter(KeyEvent.VK_PERIOD);
if (character == '!')
typeShiftCharacter(KeyEvent.VK_1);
if (character == '?')
typeShiftCharacter(KeyEvent.VK_SLASH);
if (character == ',')
typeCharacter(KeyEvent.VK_COMMA);
//More specials here as needed
}
private void typeCharacter(int character){
robot.keyPress(character);
}
private void typeShiftCharacter(int character){
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(character);
robot.keyRelease(KeyEvent.VK_SHIFT);
}
}
回答by Dombrovski
This is how I managed to use all available keys. Create a Map and fill the map using the method fillKeyMap. Now you can use String representation of key events and convert it back into KeyEvent codes using the map.
这就是我设法使用所有可用密钥的方式。创建一个 Map 并使用 fillKeyMap 方法填充该地图。现在您可以使用键事件的字符串表示,并使用映射将其转换回 KeyEvent 代码。
/** Create map with string values to integer pairs
*/
public static final void fillKeyMap(Map<String, Integer> into) {
try {
Field[] fields = KeyEvent.class.getDeclaredFields();
for(Field f : fields) {
if(f.getName().startsWith("VK_")) { //we only want these fields
int code = ((Integer)f.get(null)).intValue();
into.put(f.getName().substring(3), code);
}
}
} catch(Exception ex) {}
}
回答by Carl Bosch
I used the clipboard to solve the problem...
我用剪贴板解决了这个问题......
public static void type(String characters) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection stringSelection = new StringSelection( characters );
clipboard.setContents(stringSelection, clipboardOwner);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
}
回答by Gregory Peck
I had the same issue. I found that the code below was a simple way to translate a string into key events. It seems that most people had very implementation specific fixes to account for the differences between lower & upper case. Because the VK keys don't care about upper/lower case, casting everything to upper case seems to fix the problem.
我遇到过同样的问题。我发现下面的代码是一种将字符串转换为关键事件的简单方法。似乎大多数人都有非常具体的实现来解决小写和大写之间的差异。因为 VK 键不关心大小写,所以将所有内容都转换为大写似乎可以解决问题。
for(int i = 0; i < string.length(); i++){
char c = Character.toUpperCase(s.charAt(i));
KeyEvent ke = new KeyEvent(source, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, (int)c, c);
//do whatever with key event
}
I also wanted to say this works well for letters and number, but it may not work for other characters. This technique translated the accent/backtick mark into numberpad 0 (VK_NUMPAD0
)
我还想说这适用于字母和数字,但可能不适用于其他字符。此技术将重音/反引号标记为数字键盘 0 ( VK_NUMPAD0
)
回答by Ryan Hilbert
I recently wrote a class to do this. It enters the Alt code of each character, instead of figuring out the key combination for every case individually. Not the fastest solution, but it's concise and works for a very wide range of characters.
我最近写了一个类来做到这一点。它输入每个字符的 Alt 代码,而不是单独计算每个案例的组合键。不是最快的解决方案,但它简洁且适用于非常广泛的字符。
import java.awt.AWTException;
import java.awt.Robot;
import static java.awt.event.KeyEvent.VK_ALT;
import static java.awt.event.KeyEvent.VK_NUMPAD0;
public class Altbot extends Robot{
Altbot()throws AWTException{}
public void type(CharSequence cs){
for(int i=0;i<cs.length();i++){
type(cs.charAt(i));
}
}
public void type(char c){
keyPress(VK_ALT);
keyPress(VK_NUMPAD0);
keyRelease(VK_NUMPAD0);
String altCode=Integer.toString(c);
for(int i=0;i<altCode.length();i++){
c=(char)(altCode.charAt(i)+'0');
//delay(20);//may be needed for certain applications
keyPress(c);
//delay(20);//uncomment if necessary
keyRelease(c);
}
keyRelease(VK_ALT);
}
}