java 控制鼠标 键盘
(2009-02-24 17:13:01)
标签:
java鼠标控制键盘控制it |
分类: JAVA |
java在windows消息控制方面没有C++,C#等有正宗优势,但也有方便的实现方法。主要是通过Robot类实现,这是Sun出于自动测试目的制造的类。可以实现键盘自动输入的事件,鼠标移动点击,完成屏幕上对运行中的应用程序进行直观操作,若将事件编码成脚本然后逐一执行就可以实现无人职守的自动输入效果,但要做到和接收到输入结果的程序进行更深层次的信息控制,java还是需要通过C++,C#进行一些辅助实现的。
程序脚本如下
public class MyRobot {
Robot
robot;
EventMap
eventMap;
public void
delay(int delay) {
robot.delay(delay);
}
public int
getAutoDelay() {
return
robot.getAutoDelay();
}
public void
setAutoDelay(int autoDelay) {
robot.setAutoDelay(autoDelay);
if
(autoDelay < 20)
System.out.println("自动延迟时间太小,可能影响应用程序响应键盘鼠标事件的准确性!");
}
public
MyRobot() {
try {
robot = new
Robot();
eventMap =
new EventMap();
setAutoDelay(30);
} catch
(AWTException e) {
e.printStackTrace();
}
}
public void
exec(String cmd, int delay) {
try {
System.out.println("执行: " + cmd);
Runtime.getRuntime().exec(cmd);
delay(1000);
} catch
(IOException e) {
e.printStackTrace();
}
}
}
----- ----------
public class EventMap {
public
HashMap<String, Integer> keyEvent =
new HashMap<String, Integer>();
public
HashMap<String, Integer> mouseEvent =
new HashMap<String, Integer>();
public
HashMap<String, Integer> inputEvent =
new HashMap<String, Integer>();
public
HashMap<String, String> vkMap = new
HashMap<String, String>();
public
HashMap<String, String> vkShift = new
HashMap<String, String>();
public
EventMap() {
//
键盘事件对应值,参考javadoc文档 /docs/api/constant-values.html
keyEvent.put("CHAR_UNDEFINED", 65535);
keyEvent.put("KEY_FIRST", 400);
keyEvent.put("KEY_LAST", 402);
keyEvent.put("KEY_LOCATION_LEFT", 2);
keyEvent.put("KEY_LOCATION_NUMPAD", 4);
keyEvent.put("KEY_LOCATION_RIGHT", 3);
程序脚本如下
public class MyRobot {
}
----- ----------
public class EventMap {