Search code examples
javaawtrobot

Why doesn't CTRL+C (simulated with Awt.Robot) work properly?


I have read a web page frame from a browser with a following routine and gain all time a same result (first time copied part of the page):

  1. Move a mouse to a frame
  2. Select a text with a triple click
  3. Copy text with simulated CTRL+C keyboard press event
  4. Print copied text
  5. Go to step #1 if mouse is still in the frame

For implementation details see code below:

final static int TIME_CONST = 10;
final static int STEP_Y = 10;
int x = 100; 
int y = 50;
int count = 0;
Robot robot = new Robot();

while(y < 600) {
    robot.mouseMove(x, y);
    y += STEP_Y;
    Thread.sleep(TIME_CONST); 

    // Select text with triple mouse click
    robot.mousePress( InputEvent.BUTTON1_MASK ); 
    robot.mouseRelease( InputEvent.BUTTON1_MASK ); 
    robot.mousePress( InputEvent.BUTTON1_MASK ); 
    robot.mouseRelease( InputEvent.BUTTON1_MASK );
    robot.mousePress( InputEvent.BUTTON1_MASK ); 
    robot.mouseRelease( InputEvent.BUTTON1_MASK );
    Thread.sleep(TIME_CONST);   

    Sequence(robot, 5, KeyEvent.CTRL_MASK, KeyEvent.VK_C);
    Thread.sleep(TIME_CONST); 

    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();             
    Transferable contents = clipboard.getContents(clipboard);           
    boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor);

    String copyResult = "";
    if(hasTransferableText) {
        copyResult = (String) contents.getTransferData(DataFlavor.stringFlavor);
    }

    System.out.println("#"+(count++)+": " + copyResult);
} 

Solution

  • This should work:

    instance.keyPress(KeyEvent.VK_CONTROL);
    Thread.sleep(200); 
    instance.keyPress(KeyEvent.VK_C); 
    Thread.sleep(200); 
    instance.keyRelease(KeyEvent.VK_C); 
    Thread.sleep(200); 
    instance.keyRelease(KeyEvent.VK_CONTROL); 
    Thread.sleep(200);
    

    KeyEvent.VK_CONTROL instead of KeyEvent.CTRL_MASK