为什么CTRL + C(用Awt.Robot模拟)不能正常工作?

时间:2014-06-16 13:47:10

标签: java awtrobot

我已经使用以下例程从浏览器中读取了一个网页框架,并且获得了相同的结果(第一次复制了部分页面):

  1. 将鼠标移动到框架
  2. 选择带有三击的文字
  3. 使用模拟的CTRL + C键盘按下事件复制文本
  4. 打印复制的文字
  5. 如果鼠标仍在框架中,请转到步骤#1
  6. 有关实施细节,请参阅以下代码:

    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);
    } 
    

1 个答案:

答案 0 :(得分:1)

这应该有效:

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而不是KeyEvent.CTRL_MASK