【发布时间】:2013-01-13 18:22:51
【问题描述】:
根据之前的链接 (How to send keyboard outputs),Java 可以使用 Robot 类模拟按下的键。但是,如何模拟按键组合呢?如果我想发送组合“alt-123”,这可以使用 Robot 吗?
【问题讨论】:
标签: java awt keypress awtrobot
根据之前的链接 (How to send keyboard outputs),Java 可以使用 Robot 类模拟按下的键。但是,如何模拟按键组合呢?如果我想发送组合“alt-123”,这可以使用 Robot 吗?
【问题讨论】:
标签: java awt keypress awtrobot
对于使用 java.awt.Robot 发送组合键,我可以使用以下代码
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class VirtualKeyBoard extends Robot
{
public VirtualKeyBoard() throws AWTException
{
super();
}
public void pressKeys(String keysCombination) throws IllegalArgumentException
{
for (String key : keysCombination.split("\\+"))
{
try
{ System.out.println(key);
this.keyPress((int) KeyEvent.class.getField("VK_" + key.toUpperCase()).getInt(null));
} catch (IllegalAccessException e)
{
e.printStackTrace();
}catch(NoSuchFieldException e )
{
throw new IllegalArgumentException(key.toUpperCase()+" is invalid key\n"+"VK_"+key.toUpperCase() + " is not defined in java.awt.event.KeyEvent");
}
}
}
public void releaseKeys(String keysConbination) throws IllegalArgumentException
{
for (String key : keysConbination.split("\\+"))
{
try
{ // KeyRelease method inherited from java.awt.Robot
this.keyRelease((int) KeyEvent.class.getField("VK_" + key.toUpperCase()).getInt(null));
} catch (IllegalAccessException e)
{
e.printStackTrace();
}catch(NoSuchFieldException e )
{
throw new IllegalArgumentException(key.toUpperCase()+" is invalid key\n"+"VK_"+key.toUpperCase() + " is not defined in java.awt.event.KeyEvent");
}
}
}
public static void main(String[] args) throws AWTException
{
VirtualKeyBoard kb = new VirtualKeyBoard();
String keyCombination = "control+a"; // select all text on screen
//String keyCombination = "shift+a+1+c"; // types A!C on screen
// For your case
//String keyCombination = "alt+1+2+3";
kb.pressKeys(keyCombination);
kb.releaseKeys(keyCombination);
}
}
【讨论】:
此代码太接近原生 Windows 键盘。甚至 Api 键盘“按下”也将进入 Eclipse ide,因为它们通常会从 ide 按下。密钥是从当前调试的应用程序生成的!! (jdk 1.8, win 7, hp)
【讨论】:
简单的答案是肯定的。基本上,您需要将 Alt 的 keyPress/Release 包裹在另一个 keyPress/Releases
public class TestRobotKeys {
private Robot robot;
public static void main(String[] args) {
new TestRobotKeys();
}
public TestRobotKeys() {
try {
robot = new Robot();
robot.setAutoDelay(250);
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_2);
robot.keyRelease(KeyEvent.VK_2);
robot.keyPress(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_4);
robot.keyRelease(KeyEvent.VK_ALT);
} catch (AWTException ex) {
ex.printStackTrace();
}
}
}
【讨论】:
这是一个例子
Robot r = new Robot();
Thread.sleep(1000);
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_NUMPAD1);
r.keyPress(KeyEvent.VK_NUMPAD2);
r.keyPress(KeyEvent.VK_NUMPAD3);
r.keyRelease(KeyEvent.VK_ALT);
别忘了释放一些特殊的键,它会在你的机器上做一些疯狂的事情
【讨论】: