Robot - keyPress(KeyEvent ke)

Hello!
I'm trying to copy some text from another application.
First I move the mouse to the proper position, click into the text box and than press down the shift key and control key (and hold them down both), then is pressed the right arow key 7 times and ctrl and shift key are released. Than comes key commands for copying the text but my code doesn't marks the text!
Here's the code:
    r.mouseMove(864, 198);
    r.mousePress(InputEvent.BUTTON1_MASK);
    r.mouseRelease(InputEvent.BUTTON1_MASK);
    r.keyPress(KeyEvent.VK_CONTROL);
    r.keyPress(KeyEvent.VK_SHIFT);
    for (int i = 0; i < 7; i++) {
      r.keyPress(KeyEvent.VK_RIGHT);
      r.keyRelease(KeyEvent.VK_RIGHT);
    r.keyRelease(KeyEvent.VK_SHIFT);
    r.keyRelease(KeyEvent.VK_CONTROL);
    // r is instance of a Robot classThanks for future help!
Tilen

Sorry ... I should post this in awt section. Do not reply here, reply there please.

Similar Messages

  • Robot class not working

    I need to make a macro with the robot class that draws a picture in a paint program. For each color in the image (256 colors total) it should change the paint color and drawing each 2x2 pixel that's that color. I made the program and it works correctly for about an hour, but then it starts slowing down a LOT, entering the wrong color codes, and drawing single pixels instead of 2x2.
    Here is the code for changing the color:
    robot.mouseMove (535, 504);
    robot.mousePress (InputEvent.BUTTON1_MASK);
    robot.mouseRelease (InputEvent.BUTTON1_MASK);
    robot.mouseMove (568, 410);
    robot.mousePress (InputEvent.BUTTON1_MASK);
    robot.mouseRelease (InputEvent.BUTTON1_MASK);
    robot.mousePress (InputEvent.BUTTON1_MASK);
    robot.mouseRelease (InputEvent.BUTTON1_MASK);
    for (i = 0; i < 6; i++)
        robot.keyPress (color.toUpperCase ().charAt (i));
    robot.keyPress (KeyEvent.VK_ENTER);
    robot.keyRelease (KeyEvent.VK_ENTER);Here is the code for drawing each pixel:
    robot.mouseMove (415 + (w * 2), 185 + (h * 2) - 1);
    robot.mousePress (InputEvent.BUTTON1_MASK);
    robot.mouseMove (415 + (w * 2), 185 + (h * 2) + 1);
    robot.delay (100);
    robot.mouseRelease (InputEvent.BUTTON1_MASK);Does anyone know why the robot stops working after about an hour?

    I'll guess that this might have something to do with it:
    for (i = 0; i < 6; i++)
        robot.keyPress (color.toUpperCase ().charAt (i));
        //need to release the key!
        robot.keyRelease (color.toUpperCase ().charAt (i));
    }Also, about your code to draw one pixel: it draws three pixels in a vertical line, at least in my paint program.

  • Doing Shift-End using Robot class

    I am trying to use the Robot class to do a Shift-End in order to select the text in a window from the cursor to the end of the line. However, the following code only moves the cursor to the end of the line without selecting the text.
    robot.keyPress(KeyEvent.VK_SHIFT);
    robot.keyPress(KeyEvent.VK_END);
    robot.keyRelease(KeyEvent.VK_END);
    robot.keyRelease(KeyEvent.VK_SHIFT);
    Note that I have been able to make the following code work. So the problem with the code above does not seem to be with the Shift key per se or with the ordering of the statements.
    robot.keyPress(KeyEvent.VK_SHIFT);
    robot.keyPress(KeyEvent.VK_A);
    robot.keyRelease(KeyEvent.VK_A);
    robot.keyRelease(KeyEvent.VK_SHIFT);
    Any idea how to make the Shift-End work? I am using an XP PC.

    My ENTIRE code follows. Not surprisingly, the shiftEnd.actionPerformed gets a nullPointerException during execution. And being new to Java, I get the feeling I might be missing a whole bunch of stuff. For example, do I need to register for events? Do I need to generate a shift-End ActionEvent somehow? It is only the last 4 lines that are at issue here. Everything down to that point accomplishes what I want, i.e., position the mouse in a text window in the upper right-hand corner of my screen, move the cursor to the top of that window, then go down 5 lines. At that point, I want to do the shift-End to select all text in the line.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.KeyStroke;
    import javax.swing.JTextField;
    public class KeyStrokeTest {
    /** Creates a new instance of KeyStrokeTest */
    public KeyStrokeTest() {
    * @param args the command line arguments
    public static void main(String[] args)
    throws AWTException{
    Robot robot = new Robot();
    // Position mouse over Test Director test
    robot.mouseMove(600,300);
    // Press and release left mouse button to set focus in Test Director test
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    // Go to top of Test Director test
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_HOME);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_HOME);
    // Go down to first line of request
    for(int i=0;i<5;i++) {
    robot.keyPress(KeyEvent.VK_DOWN);
    robot.keyRelease(KeyEvent.VK_DOWN);
    robot.delay(1000);
    // Do a shift End
    KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_END,KeyEvent.VK_SHIFT);
    JTextField textComponent = new JTextField("String");
    ActionListener shiftEnd = textComponent.getActionForKeyStroke( keyStroke );
    shiftEnd.actionPerformed( null );

  • Invalid Keycodes on primary keys (Robot)

    I have a Robot that is working quite well until I needed to use the '[' and ']' characters :
    robot.keyPress(KeyEvent.VK_OPEN_BRACKET);
    Which generates invalid keycode exeptions. I undestand the need to press and release shift for non-primary keys (eg. ?) and I do this with my robot a few times, but I don't understand why I am unable to get my robot to type brackets.
    I had a similar problem with VK_SLASH, but VK_DIVIDE was an adequate substitute. :)

    Ahh replying to oneself, how embarrassing.
    Churning through the forums I found a post that said if you make a JFrame, set it visible, and dispose of it it eliminates the invalid keycode exceptions. Now I have:
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.dispose();
    robot.keyPress(KeyEvent.VK_OPEN_BRACKET);
    robot.keyPress(KeyEvent.VK_CLOSE_BRACKET);
    and it works like a charm. This is one of the stranger bugs/solutions I've come across in my life, and I'm intensely curious as to why this solution works. Any ideas?

  • How to write Robot program?

    It's the code:
    try {
    Robot RobotTest = new Robot();
    catch (Exception ex) {
    System.out.println("Robot Err");
    RobotTest.mouseMove(10,10);
    RobotTest.delay(1000);
    RobotTest.mouseMove(50,50);
    RobotTest.delay(1000);
    RobotTest.mouseMove(90,90);
    but the mouse cursor doesn't act as i wish!
    can anyone please tell me what's wrong? Thanks!!

    Please use the [ code ] and [ /code ] tags to format the code to make it easier to read.
    I already had a Robot test program. I just pasted you code at the end. It appears to work OK to me, as I see the mouse cursor move.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestRobot extends JFrame
         public TestRobot()
              JPanel panel = new JPanel();
              setContentPane( panel );
              panel.add( new JLabel( "Label:" ) );
              panel.add( new JTextField(15) );
         public static void main(String[] args)
              throws Exception
              JFrame frame = new TestRobot();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.pack();
              frame.show();
              Robot robot = new Robot();
              robot.setAutoDelay(500);
              // maximize the frame
              robot.mouseMove(15, 15 );
              robot.mousePress(InputEvent.BUTTON1_MASK);
              robot.mouseRelease(InputEvent.BUTTON1_MASK);
              robot.keyPress(KeyEvent.VK_X);
              // enter data in text field
              robot.keyPress(KeyEvent.VK_A);
              robot.keyPress(KeyEvent.VK_B);
              robot.keyPress(KeyEvent.VK_C);
              robot.keyPress(KeyEvent.VK_SHIFT);
              robot.keyPress(KeyEvent.VK_2);
              robot.keyPress(KeyEvent.VK_PERIOD);
              robot.keyRelease(KeyEvent.VK_SHIFT);
              robot.keyPress(KeyEvent.VK_PERIOD);
              // move the mouse
              robot.delay(1000);
              robot.mouseMove(10,10);
              robot.delay(1000);
              robot.mouseMove(50,50);
              robot.delay(1000);
              robot.mouseMove(90,90);
    }

  • Continue after Robot has finished typing

    Hi,
    I have found a basic example of the Robot class:
    public class RobotExample {   
        public static void main(String[] args) {       
            try {           
                Robot robot = new Robot();
                // Robot start writting
                robot.keyPress(KeyEvent.VK_H);
                robot.keyPress(KeyEvent.VK_I);
                robot.keyPress(KeyEvent.VK_SPACE);
                robot.keyPress(KeyEvent.VK_B);
                robot.keyPress(KeyEvent.VK_U);
                robot.keyPress(KeyEvent.VK_D);
                robot.keyPress(KeyEvent.VK_Y);           
            } catch (AWTException e) {
                e.printStackTrace();
        // Code that follows needs to ensure that the Robot has finished typing
    }The code that immediately follows the Key Presses remove focus from where the robot is typing so it would be nice to detect when the Robot has finished typing before I continue. At the moment the best way I can think of would be to simply place all the Key Presses in a Thread, telling it to sleep once it had finished. The problem with that is there could still be a problem with the amount of time being too much or too little and no way of finding out.
    Does any one have any ideas how I can listen to the Robot events and continue once they have finished?
    Thanks

    Note: This thread was originally posted in the [Java Programming|http://forums.sun.com/forum.jspa?forumID=31] forum, but moved to this forum for closer topic alignment.

  • Print html document

    Hi, I'm trying to print a html document with this following java code but doesn't works:
      public void onActionPrintEncuestaPDF(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionPrintEncuestaPDF(ServerEvent)
         try{
              Robot robot = new Robot();
              // Ctrl+P
              robot.keyPress(KeyEvent.VK_CONTROL );          
              robot.keyPress(KeyEvent.VK_P );          
              robot.keyRelease(KeyEvent.VK_CONTROL);
              robot.keyRelease(KeyEvent.VK_P );
              Thread.sleep(500);
              //Alt+U
              robot.keyPress(KeyEvent.VK_ALT );
              robot.keyPress(KeyEvent.VK_U );
              robot.keyRelease(KeyEvent.VK_ALT );
              robot.keyRelease(KeyEvent.VK_U );
              Thread.sleep(500);
              //entrée
              robot.keyPress(KeyEvent.VK_ENTER);
              robot.keyRelease(KeyEvent.VK_ENTER );
              Thread.sleep(500);
         catch(Exception e){  }
        //@@end
    This is not working because java.awt.Robot is a part of AWT package and intended for the client site, how I can make an action that when the
    client push the print button. Print the html document automatly.
    Regards,
    Gabriel

    I create into KM Content on portal a file called print.html and I put the following code:
    &#65279;<html>
      <head />
      <body onLoad="window.parent.focus(); window.parent.print();">
      </body>
    </html>
    Because window.paren.print(); printed the code of actual iFrame. And into Web Dynpro I created a button that call the following function.
    public void onActionPrintEncuestaPDF(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionPrintEncuestaPDF(ServerEvent)     wdContext.currentPrintElement().setAtrURL("/irj/go/km/docs/documents/print/print.html");
       //@@end

  • How to call keys CTRL+P in WebDynpro Java

    Hi,
    I'm trying to print a html document into Web Dynpro but for me it's very difficult cause is a dinamically content with a lot of text. So I would like  when a push the button print call the keys CTRL+P. It's possible?
    Thanks and sorry for my English!

    It's possible and how?
    This the solution.... One hour after I find the solution.
    public void onActionPrint(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionPrintEncuestaPDF(ServerEvent)
        try{
              Robot robot = new Robot();
              //CTRL+P
              robot.keyPress(KeyEvent.VK_CONTROL );
              robot.keyPress(KeyEvent.VK_P );
              robot.keyRelease(KeyEvent.VK_CONTROL );
              robot.keyRelease(KeyEvent.VK_P );
              //Alt+U
              robot.keyPress(KeyEvent.VK_ALT );
              robot.keyPress(KeyEvent.VK_U );
              robot.keyRelease(KeyEvent.VK_ALT );
              robot.keyRelease(KeyEvent.VK_U );
              //ENTER
              robot.keyPress(KeyEvent.VK_ENTER);
              robot.keyRelease(KeyEvent.VK_ENTER );
    catch(Exception e){  }
    Thanks

  • How to capture the web:input_email element?

    while i try to capture the input box which is the type of "email" but its getting captured as web.element
    web.element(
      112,
      "/web:window[@index='0' or @title='salesforce.com - Customer Secure Login Page']/web:document[@index='0']/web:form[@name='login' or @index='0']/web:input_email[@placeholder='User Name' and @value='[email protected]' and @name='username' and @id='username' and @onkeyup=\"if(this.value != &apos;&apos;){document.getElementById(&apos;clrUsr&apos;).style.display=&apos;block&apos;;}else{document.getElementById(&apos;clrUsr&apos;).style.display=&apos;none&apos;;}\" and @className='input' and @disabled='false' and @tabIndex='0' and @checked='false' and @defaultChecked='false' and @maxLength='-1' and @readOnly='false' and @selectionEnd='18' and @selectionStart='18' and @size='20' and @textLength='18' and @index='0']")
      .pressTab();
    i want to set the value of textbox which is the email. In IE it is recognized as textbox but in Firefox it is recognized as web.element.
    Thanks in advance.

    I also have similar problems with my phone and email field
    I used this temporary solution. Can you please let me know if u find any?
    had to write the below script to make it work. But has any body come across the issue?
    Defeing robot and keyevent
    web.textBox(34, "{{obj.ATG_repo.SIGNUP_email}}").keyPress("abc<SHIFT-2>example");
    robot.keyPress(KeyEvent.VK_DECIMAL);
    web.textBox(34, "{{obj.ATG_repo.SIGNUP_email}}").keyPress("com");

  • Problem in server program

    Hi
    My client prog runs in an infinite loop where it captures the screen and creates an image object.
    After that it sends the image object to the server prog.
    Server program receives it and displays it using Jframe , that is it uses a panel and a button named paste.
    So I have used an infinite loop in the server side as well.
    Problem is as long as client is running the interface that i used for pasting , pops up but I cant see the paste button
    Its only when I close the client side the paste button becomes visible and its also working.
    but I need to paste it even when the client side is running.
    Any idea where am I going wrong?
    The relevant codes are as follows----
    SERVER:
    public class Test
         public Test() {
         try {
         ServerSocket ser=new ServerSocket(4444);     
         ImageIcon img=new ImageIcon();
         String s1="1";
         for(;;){
            Socket clisoc=ser.accept();     
            DataOutputStream os1 = new DataOutputStream(clisoc.getOutputStream());
            os1.writeUTF(s1);
           ObjectInputStream oin = new ObjectInputStream(clisoc.getInputStream());
            img=(ImageIcon)oin.readObject();
            Image i =img.getImage();
           Test1 e = new Test1(i);
            System.out.println(i);
         os1.close();
         oin.close();
         clisoc.close();
         }catch(Exception e){}
    }Test1 class is used for creating the image from the image object.
    CLIENT---
    public final class Test2 implements ClipboardOwner{
        public static void main (String[]  aArguments ){
         try{
              String s1;
              for(;;){
        Socket clisoc= new Socket("localhost",4444);
        TextTransfer textTransfer = new TextTransfer();
        DataInputStream dis=new DataInputStream(clisoc.getInputStream());
        s1=dis.readUTF();
        if(s1.equals("1")){
        Robot robot=new Robot();
        robot.keyPress(KeyEvent.VK_PRINTSCREEN);
        robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
        BufferedImage g=(textTransfer.getClipboard());
        ImageIcon ic = new ImageIcon(g);
        System.out.println(ic);   
        ObjectOutputStream oos = new ObjectOutputStream(clisoc.getOutputStream());
        Thread.sleep(9000);
        oos.writeObject(ic);
        dis.close();
        oos.close();
        clisoc.close();     
       else
         continue;
        }catch(Exception e){System.out.println(e);}
       }    getClipboard() is the function to catch the clipboard content.
    Thanks in advance.

    Thanks for replying.
    I got rid of the problem by introducing a similar if-else block in the server side as well.
    Now I also dont have any Thread.sleep() in either client or server program.
    The interface that I used to paste the image pops up alright but the paste button takes almost 3 minutes to appear.
    Is it normal in windows 98 (P4)?Mind you , the button is working fine.
    would you specify why should I "get rid of other close statements" except oos.close()?
    I solved my previous problem by keeping them as it is.

  • How to generate key events programmatically

    Hello friends,
    I am developing an application that would automaticall trigger some keboard events for this purpose i would like to trigger an event like alt+f4 i.e pressing alt+f4 together
    How can we do this using java
    regards
    hari

    You should be able to use the java.awt.Robot class to perform programmatic UI events.
    It doesn't seem that it permits use to do things like keyPress("alt-f4") so you might have to do something like this:
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_F4);
    robot.keyRelease(KeyEvent.VK_F4);
    robot.keyRelease(KeyEvent.VK_ALT);Hope this helps.

  • Strange class error when using java

    I've been attempting to use java.awt.robot to simulate a key press when a button is clicked however I'm getting a couple of errors that I can't figure out but I'm not so good when it comes to scripts. When the button "LetterButton" is pressed it should simulate a keypress, ideally to the desktop/operating sytem but the errors I'm getting are:-
    1071: Syntax error: expected a definition keyword (such as function) after attribute public, not static.
    1084: Syntax error: expecting rightbrace before leftbrace.
    1131: Class must not be nested.
    Here's the code:-
    <?xml version="1.0" encoding="utf-8"?><mx:WindowedApplicationxmlns:mx="
    http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
    <![CDATA[
    import java.awt.Robot; 
    import java.awt.event.KeyEvent; 
    public class Main { 
    public static void main(String[] argv) throws Exception { 
    Robot robot =
    new Robot(); 
    robot.keyPress(KeyEvent.VK_A);
    robot.keyRelease(KeyEvent.VK_A);
    ]]>
    </mx:Script>
    <mx:VBox x="359" y="262" horizontalCenter="0" verticalCenter="0">
    <mx:Button id="LetterButton" label="Button" click=""/>
    <mx:TextInput id="txt"/>
    </mx:VBox></mx:WindowedApplication>

    Sounds tricky. I may ask them to look for an alternative way of doing it as Java really isn't my thing, I'm merely just a flex beginner at the moment.
    The reason I've been looking for this is that my app will be installed on a digital tv that also has a system connected to it using a Linux operating system so the user can switch between watching digital tv and the application seamlessly and at the moment a Linux professional who I'm working with has the Digital TV bound to the F12 key which is bound to a handheld remote control (being a tv there is no keyboard, just an 'air mouse' and the remote control).
    So my client and my Linux guy have asked me to come up with a way of getting the app to communicate with the desktop/operating system. I have seen flex apps in the past where a user can drag and drop videos on their desktop into an air application from which they will be played so I thought it would be possible to interact with the exteral OS/Desktop from within an AIR app by using just flex but it doesn't seem so easy through my research.
    Thanks for your help though.

  • Select 2 records (rows) in the results.

    I am using Oracle R12- Forms.
    After searched for all orders for a specific Customer, on the Results, I need to select 2 different rows.
    Also tried ft object,but failed.
    If manual, I use Keep holding the Ctrl Key, and Click for the first row, and Click 2nd row.
    In OATS, I could not do this with the code below:
    int rone=2;
    int rtwo=5
    Robot robot = new Robot();
    robot.delay(5000);
    // press and hold CONTROL key
    robot.keyPress(KeyEvent.VK_CONTROL);      
    forms.textField("//forms:textField[(@name='MY_ORDER_NUM_"+rone+"')]").click();          
    forms.textField("//forms:textField[(@name='MY_ORDER_NUM_"+rtwo+"')]").click();
    robot.keyRelease(KeyEvent.VK_CONTROL);
    Any help is greatly appreciated.
    Thanks,

    What you need is a tree.
    See Tomahawk (www.myfaces.org)

  • How to convert a string into a collection of KeyEvents

    I'm working on a program that must interact with a 3rd party application (closed to me, I have no access to the code or anything like that). I have been unable to send data to the program by getting its OutputStream. The only thing that has worked was using a Robot object to send individual key events (i.e. robot.keyPress(KeyEvent.VK_A);). Therefore I'm looking to convert a string (many different strings actually) into a collection of their associated KeyEvents so I can send them to the other application. Does anyone know a good way of doing it, or is anyone able to help me with using the OutputStream?
    Thank you!
    (The 3rd party application is Attachmate InfoConnect, a Unisys terminal emulation program that I have to use to access a mainframe).

    Here is a code sample.     public void checknumber(int vsize){
    int total;
    String anum;
    anum = tf2.getText();
    validnumber = true;
    lines2combine = 1;     //default (an integer)
    recs2make = 1;          //default
    try{
    lines2combine = Integer.parseInt(anum);
    catch (NumberFormatException e){
              System.out.println("Entry for lines to combine not numeric");
         validnumber = false;
         d1Title = "Data Entry Error";
         d1Txt = "For number for lines to combine;";
         d2Txt = "Enter a number.";
         doMessage();

  • Creating a Java GUI for a C/C++ program

    I'm tasked with creating a GUI for a multi-threaded C++ network server program that has it's main function running with a while loop that checks for keystrokes from the user. The C++ code for the loop is basically:
    while(i!='q')
    if(kbhit())
    i=getch();
    processkey(i);
    }And the processkey function performs different actions based on the key that was pressed.
    I was reading up on ways to interface between Java and C/C++ and heard of JNI, but I also found someone who suggested using the Java Robot class to send the keystrokes from my GUI to the C++ program.
    I've been trying to make a small test case application using the Robot class before trying to implement it in my larger project.
    I created a program with a JFrame with two buttons, one starts a simple C++ program that loops, waiting for keypresses and which will close when 'q' is pressed, like my main program.
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            try {
                Runtime.getRuntime().exec("C:/Users/Administrator1/Desktop/Untitled2.exe");
                // TODO add your handling code here:
            } catch (IOException ex) {
                Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
            // TODO add your handling code here:
        }The other button creates a Robot instance and tells that robot to send a key press of 'q', which should terminate the C++ program.
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
            try {
                Robot robot = new Robot();
                // Creates the delay of 5 sec so that you can open notepad before
                // Robot start writting
                //robot.delay(5000);
                robot.keyPress(KeyEvent.VK_Q);
            } catch (AWTException e) {
                e.printStackTrace();
        }It isn't working though. Could it be because when the program is started from my Java app, it runs in the background rather than opening in a new command prompt window? Or is Robot not the way to go, and if so, are there any examples and/or tutorials online that could help me?

    When you clicked the button, what application do you think has the focus at that point? So what do you think consumes the keystroke that you emulated? Hint: It wouldn't be the application you intended it to go to.

Maybe you are looking for