文章字数:474,阅读全文大约需要1分钟
java.awt.Robot 提供模拟点击,模拟用户输入等操作
引入
1 2 3
| import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent;
|
键盘操作
- 按下按键
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
public static final void pressSingleKeyByNumber(int keycode) { try { Robot robot = new Robot(); robot.keyPress(keycode); robot.keyRelease(keycode); robot.delay(500); } catch (AWTException e) { e.printStackTrace(); } }
|
- 组合键
1 2 3 4 5 6 7
| Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(keycode); robot.keyRelease(keycode); robot.keyRelease(KeyEvent.VK_CONTROL); robot.delay(100);
|
鼠标操作
- 点击
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
public static final void clickScreenByXY(Integer x, Integer y) { try { Toolkit toolkit = Toolkit.getDefaultToolkit(); Robot robot = new Robot(); if (x == null) { x = toolkit.getScreenSize().width / 2; } if (y == null) { y = toolkit.getScreenSize().height / 2; }
robot.mouseMove(x, y); robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); robot.delay(100); } catch (AWTException e) { e.printStackTrace(); } }
|
- 移动鼠标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
public static final void mouseMoveToXY(Integer x, Integer y) { try { Toolkit toolkit = Toolkit.getDefaultToolkit(); Robot robot = new Robot(); if (x == null) { x = toolkit.getScreenSize().width; } if (y == null) { y = toolkit.getScreenSize().height / 2; }
robot.mouseMove(x, y); robot.delay(100); } catch (AWTException e) { e.printStackTrace(); } }
|
常用按键
按键都在 KeyEvent类中,和键盘对应