Executing Commands


Having read all the commands to execute, you can loop over those commands with a for loop. Each command, such as t:abc, which sends the text "abc" to the program the Robot project is controlling, is made up of an operation ("t" for text here) and data ("abc" here).

Here's how the Robot project extracts the operation and data from each command as it loops over all commands:

 public void actionPerformed(ActionEvent e)  {     try{         .         .         .         for (int loopIndex = 0; loopIndex < numberCommands;             loopIndex++){             String operation = commands[loopIndex].substring(0, 1);             String data = commands[loopIndex].substring(2);         .         .         . 

Sending Keystrokes

Each command is a single character, so you can use a switch statement to handle them all. Each operation corresponds to a method of the Robot classfor example, to send text with the t operation, you can use the keyPress method.

If the data is "ALTDN", the user wants to press the Alt key, which you can do by calling robot.keyPress(KeyEvent.VK_ALT). That's how you send textby converting it to constants using the KeyEvent class's fields, such as VK_A, VK_B, VK_ALT, and so forth. Here's what it looks like in the code when the user wants to press the Alt key:

 public void actionPerformed(ActionEvent e)  {     try{         .         .         .         for (int loopIndex = 0; loopIndex < numberCommands;             loopIndex++){             String operation = commands[loopIndex].substring(0, 1);             String data = commands[loopIndex].substring(2);             switch(operation.toCharArray()[0])             {                 case 't':                     if(data.equals("ALTDN")){                         robot.keyPress(KeyEvent.VK_ALT);                      }         .         .         . 

Each of the commands that can be handled with a single keystrokepressing the Alt key, releasing the Alt key, and so onare easy to implement with the keyPress and keyRelease methods:

 switch(operation.toCharArray()[0])  {     case 't':         if(data.equals("ALTDN")){             robot.keyPress(KeyEvent.VK_ALT);         }         else if(data.equals("ALTUP")){             robot.keyRelease(KeyEvent.VK_ALT);         }         if(data.equals("CTRLDN")){             robot.keyPress(KeyEvent.VK_CONTROL);         }         else if(data.equals("CTRLUP")){             robot.keyRelease(KeyEvent.VK_CONTROL);         }         else if(data.equals("ENTER")){                 robot.keyPress(KeyEvent.VK_ENTER);                  robot.keyRelease(KeyEvent.VK_ENTER);         }         else if(data.equals("TAB")){                 robot.keyPress(KeyEvent.VK_TAB);                 robot.keyRelease(KeyEvent.VK_TAB);         }         else if(data.equals("ESCAPE")){                 robot.keyPress(KeyEvent.VK_ESCAPE);                 robot.keyRelease(KeyEvent.VK_ESCAPE);         }         .         .         . 

What about handling text strings such as "abc"? In that case, you need to break the text into individual characters and handle them one by one. In the Robot project, such text is placed into a character array named chars, and each character is looped over:

         else{             char chars[] = data.toCharArray();             for(int charIndex = 0;                 charIndex < chars.length;                 charIndex++){         .         .         .                 }         .         .         . 

You're responsible for pressing the key, releasing it, and even pressing the Shift key for capital letters. Here's what that looks like in code:

         else{             char chars[] = data.toCharArray();             for(int charIndex = 0;                 charIndex < chars.length;                 charIndex++){                 if(chars[charIndex] >= 'a' &&                     chars[charIndex] <= 'z'){                     robot.keyPress((int)                         chars[charIndex]                         - ('a' -'A'));                     robot.keyRelease((int)                          chars[charIndex]                         - ('a' -'A'));                 }                 else if(chars[charIndex] >= 'A' &&                     chars[charIndex] <= 'Z'){                     robot.keyPress(KeyEvent.VK_SHIFT);                     robot.keyPress((int)                         chars[charIndex]);                     robot.keyRelease((int) chars                         [charIndex]);                     robot.keyRelease                         (KeyEvent.VK_SHIFT);                 }         .         .         . 

If the character isn't a letter or a capital letter, the code simply passes the character code to the program it's controlling:

                 else{                 robot.keyPress((int)                     chars[charIndex]);                 robot.keyRelease((int)                     chars[charIndex]);                 robot.delay(100);                 }             }         }         break;  

You can see an example in Figure 7.2. That handles the text the user wants to send to the target program. Now what about mouse events?

Sending Mouse Events

The Java Robot class includes a number of mouse methods, such as mouseMove and mousePress, that the Robot project puts to work. For example, if the user issues a command such as "m:500,200", he wants to move the mouse pointer to (500, 200) on the screen, where (0, 0) is at upper left. To handle the "m" operation, then, you recover the x and y coordinates this way:

     case 'm':         String coords[] = data.split(",");         .         .         .         break; 

Then you convert the coordinates from text to int values, and you pass them on to the Robot class's mouseMove method:

     case 'm':         String coords[] = data.split(",");         int x = Integer.parseInt(coords[0]);         int y = Integer.parseInt(coords[1]);         robot.mouseMove(x, y);         robot.delay(500);         break; 

That moves the mouse where the user wants it. For example, you can see the mouse responding to the Robot command m:500,300 in the WordPad window shown in Figure 7.3.

Figure 7.3. The Robot moves the mouse.


Clicking the mouse is easyjust press the mouse and release it. You can select which mouse button you want to press with the InputEvent class's button masks; for the left mouse button, you use InputEvent.BUTTON1_MASK:

     case 'c':         robot.mousePress(InputEvent.BUTTON1_MASK);          robot.delay(500);         robot.mouseRelease(InputEvent.BUTTON1_MASK);         break; 

If you want to double-click the mouse, just issue two "c:" commands.

What about right-clicking the mouse? Just click the right mouse button with the use of InputEvent.BUTTON3_MASK (InputEvent.BUTTON2_MASK corresponds to the middle mouse button, if the mouse has one):

     case 'r':         robot.mousePress(InputEvent.BUTTON3_MASK);         robot.delay(500);         robot.mouseRelease(InputEvent.BUTTON3_MASK);         break;  

You can see the Robot right-clicking WordPad in Figure 7.4.

Figure 7.4. The Robot right-clicking the mouse.


Making the Robot Wait

You can make the Robot wait for as long as you like between commands, and even before running the first command at all. When the user passes a command such as w:500 to the Robot, he wants to pause for 500 seconds.

All the Robot needs to do is to parse the number of seconds to wait, multiply this by 1000 to convert to milliseconds, and then call the Java Robot class's delay method with that number:

     case 'w':          int numberSeconds = Integer.parseInt(data);         robot.delay(numberSeconds * 1000);         break;  

If you want to schedule the Robot for late at night, this is the way to do itjust make it wait the number of seconds you want to pause before beginning the action.

Making the Robot Beep

Beeping is an easy taskyou can use the Java Toolkit object's beep method. Using the default Toolkit object you get with the static getdefaultToolkit method, you can make the computer beep this way:

     case 'b':         Toolkit.getDefaultToolkit().beep();         break;  

Taking a Screenshot

When the Robot is working with your computer, especially late at night, it can be a good idea to watch what's going on. You don't even have to be presentyou can have the Robot take a screenshot for you, using the s: command.

How do you take a screenshot? First, you need to get the size of the screen in pixels, which you can do with the default Toolkit object's getScreenSize method:

     case 's':          Dimension screenSize =             Toolkit.getDefaultToolkit().             getScreenSize();         .         .         . 

To capture the screen, you can use the Java Robot class's createScreenCapture method, passing it a rectangle corresponding to the screen dimensions. This method returns a BufferedImage object holding the screenshot:

     case 's':          Dimension screenSize =             Toolkit.getDefaultToolkit().             getScreenSize();         BufferedImage bufferedImage =             robot.createScreenCapture(new                 Rectangle(screenSize));             .             .             .         break;  

BufferedImage objects are easy to store on disk, as you've already done in the Graphicizer project. You create a new File objectthe Robot saves screen captures in a file named cap.png using the PNG formatand write that file to disk with the ImageIO.write method:

     case 's':         Dimension screenSize =             Toolkit.getDefaultToolkit().             getScreenSize();         BufferedImage bufferedImage =             robot.createScreenCapture(new                 Rectangle(screenSize));         File outputFile = new File("cap.png");         ImageIO.write(bufferedImage, "PNG",             outputFile);         break;  

When you save a screen capture, two options are available by default: the PNG format and the JPG format. The Robot uses the PNG format because it's clearer and suffers from fewer distortions due to compression. If you want to use the JPG format, just switch the format used in the ImageIO.write method.



    Java After Hours(c) 10 Projects You'll Never Do at Work
    Java After Hours: 10 Projects Youll Never Do at Work
    ISBN: 0672327473
    EAN: 2147483647
    Year: 2006
    Pages: 128

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net