java.awt.Robotで遊んでみた
電卓を起動させて、Robotに電卓を操作させて、計算結果をクリップボードから取得するというサンプル。なかなか楽しい。
RobotCalcTest.java
package example.test; import java.awt.Robot; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.event.KeyEvent; import junit.framework.TestCase; import org.junit.Test; public class CalcRobotTest extends TestCase { Robot robot; Process calc; @Override protected void setUp() throws Exception { super.setUp(); //電卓を起動 ProcessBuilder builder = new ProcessBuilder("calc.exe"); calc = builder.start(); //ロボット起動 robot = new Robot(); robot.delay(1000); } @Override protected void tearDown() throws Exception { super.tearDown(); calc.destroy(); } public void testCalc() throws Exception { //関数電卓にする keyboardClick(robot, KeyEvent.VK_ALT); keyboardClick(robot, KeyEvent.VK_V); keyboardClick(robot, KeyEvent.VK_S); //16進数モード keyboardClick(robot, KeyEvent.VK_F5); // 20 - 1 = keyboardClick(robot, KeyEvent.VK_2); keyboardClick(robot, KeyEvent.VK_0); keyboardClick(robot, KeyEvent.VK_MINUS); keyboardClick(robot, KeyEvent.VK_1); keyboardClick(robot, KeyEvent.VK_EQUALS); //クリップボードにコピー keyboardClick(robot, KeyEvent.VK_CONTROL, KeyEvent.VK_C); assertEquals("1F", getClipboard()); } public void keyboardClick(Robot robot, int... args) { for (int key : args) { robot.keyPress(key); } //同時押しの場合はShift等は後に離したいので逆順 for (int i=args.length-1; i>=0; i--) { robot.keyRelease(args[i]); } robot.delay(1000); } public String getClipboard() { String result = null; try { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); result = (String)clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor); } catch (Exception e) { e.printStackTrace(); } return result; } }