2012-12-21 40 views
11

Quando si utilizza un robot Java, quando si invia una barra o barra rovesciata si genera un'eccezione.Invio di barra e barra rovesciata con Java

Ad esempio:

public void slash() throws AWTException { 
    Robot rob = new Robot(); 
    rob.keyPress(KeyEvent.VK_SLASH); 
    rob.keyRelease(KeyEvent.VK_SLASH); 
} 

public void backSlash() throws AWTException { 
    Robot rob = new Robot(); 
    rob.keyPress(KeyEvent.VK_BACK_SLASH); 
    rob.keyRelease(KeyEvent.VK_BACK_SLASH); 
} 

Poi, quando ho voglia di scrivere quelle, io uso:

public void type() { 

    try { 
     slash(); 
    } catch (AWTException e) { System.out.println("Exception when typing slash."); } 

    try { 
     backSlash(); 
    } catch (AWTException e) { System.out.println("Exception when typing back slash."); } 


} 

ottengo due messaggi di errore nella mia console. A proposito, tutte le altre sequenze di tasti che ho provato ad inviare hanno funzionato bene.

ho la stacktrace follwowing per Slash:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Invalid key code 
    at sun.awt.windows.WRobotPeer.keyPress(Native Method) 
    at java.awt.Robot.keyPress(Unknown Source) 
    at com.paschoalinoto.bruno.pastescript.Paste.slash(Paste.java:23) 
    at com.paschoalinoto.bruno.pastescript.Paste.type(Paste.java:36) 
    at com.paschoalinoto.bruno.pastescript.MainGUI$4.actionPerformed(MainGUI.java:113) 
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) 
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) 
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) 
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source) 
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) 
    at java.awt.Component.processMouseEvent(Unknown Source) 
    at javax.swing.JComponent.processMouseEvent(Unknown Source) 
    at java.awt.Component.processEvent(Unknown Source) 
    at java.awt.Container.processEvent(Unknown Source) 
    at java.awt.Component.dispatchEventImpl(Unknown Source) 
    at java.awt.Container.dispatchEventImpl(Unknown Source) 
    at java.awt.Component.dispatchEvent(Unknown Source) 
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) 
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) 
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) 
    at java.awt.Container.dispatchEventImpl(Unknown Source) 
    at java.awt.Window.dispatchEventImpl(Unknown Source) 
    at java.awt.Component.dispatchEvent(Unknown Source) 
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) 
    at java.awt.EventQueue.access$200(Unknown Source) 
    at java.awt.EventQueue$3.run(Unknown Source) 
    at java.awt.EventQueue$3.run(Unknown Source) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) 
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) 
    at java.awt.EventQueue$4.run(Unknown Source) 
    at java.awt.EventQueue$4.run(Unknown Source) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) 
    at java.awt.EventQueue.dispatchEvent(Unknown Source) 
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
    at java.awt.EventDispatchThread.run(Unknown Source) 

rovesciare il lavoro, ma anche lanciare un IllegalArgumentException:

java.lang.IllegalArgumentException: Invalid key code 
at sun.awt.windows.WRobotPeer.keyPress(Native Method) 
at java.awt.Robot.keyPress(Unknown Source) 
at com.paschoalinoto.bruno.pastescript.Paste.press(Paste.java:198) 
at com.paschoalinoto.bruno.pastescript.Paste.paste(Paste.java:173) 
at com.paschoalinoto.bruno.pastescript.Paste.finalPaste(Paste.java:227) 
at com.paschoalinoto.bruno.pastescript.MainGUI$4.actionPerformed(MainGUI.java:113) 
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) 
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) 
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) 
at javax.swing.DefaultButtonModel.setPressed(Unknown Source) 
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) 
at java.awt.Component.processMouseEvent(Unknown Source) 
at javax.swing.JComponent.processMouseEvent(Unknown Source) 
at java.awt.Component.processEvent(Unknown Source) 
at java.awt.Container.processEvent(Unknown Source) 
at java.awt.Component.dispatchEventImpl(Unknown Source) 
at java.awt.Container.dispatchEventImpl(Unknown Source) 
at java.awt.Component.dispatchEvent(Unknown Source) 
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) 
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) 
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) 
at java.awt.Container.dispatchEventImpl(Unknown Source) 
at java.awt.Window.dispatchEventImpl(Unknown Source) 
at java.awt.Component.dispatchEvent(Unknown Source) 
at java.awt.EventQueue.dispatchEventImpl(Unknown Source) 
at java.awt.EventQueue.access$200(Unknown Source) 
at java.awt.EventQueue$3.run(Unknown Source) 
at java.awt.EventQueue$3.run(Unknown Source) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) 
at java.awt.EventQueue$4.run(Unknown Source) 
at java.awt.EventQueue$4.run(Unknown Source) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) 
at java.awt.EventQueue.dispatchEvent(Unknown Source) 
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) 
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) 
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) 
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
at java.awt.EventDispatchThread.run(Unknown Source) 

C'è un modo posso inviare slash backslash sequenze di tasti?

+9

Per favore * sempre * includere il risultato di 'e.printStackTrace()' quando applicabile. – Vulcan

+2

Bene invece di stampare semplicemente che * era * un'eccezione, perché non stampare i dettagli delle eccezioni? –

+0

Ok, lo aggiungerò. –

risposta

4

Ok, ho trovato una soluzione che può essere utile per gli utenti che lavorano con layout di tastiera diversi. Usa i codici Alt.

public static void alt(int event1, int event2, int event3, int event4) throws Exception { 

    Robot bot = new Robot(); 
    bot.delay(50); //Optional 
     bot.keyPress(KeyEvent.VK_ALT); 

      bot.keyPress(event1); 
      bot.keyRelease(event1); 

      bot.keyPress(event2); 
      bot.keyRelease(event2); 

      bot.keyPress(event3); 
      bot.keyRelease(event3); 

      bot.keyPress(event4); 
      bot.keyRelease(event4); 

     bot.keyRelease(KeyEvent.VK_ALT); 

} 

Poi si chiamano in questo modo:

Per barre rovesciate: alt(KeyEvent.VK_NUMPAD0, KeyEvent.VK_NUMPAD0, KeyEvent.VK_NUMPAD9, KeyEvent.VK_NUMPAD2);

Per quelli normali: alt(KeyEvent.VK_NUMPAD0, KeyEvent.VK_NUMPAD0, KeyEvent.VK_NUMPAD4, KeyEvent.VK_NUMPAD7);

Nessuna eccezione. Funziona anche con tutti gli altri personaggi. Ma assicurati di avere Num Lock quando usi questo.

+1

+1, pensiero creativo. Contrassegnalo come accettato se è la tua soluzione finale. – Vulcan

+0

Tuttavia, per migliorare, non utilizzare un nuovo 'Robot' per ogni chiamata al metodo. – Vulcan

+0

@Vulcan Questa è una buona idea ... A proposito, grazie per il +1 –

2

(Mi dispiace dovrei dire che questa non è una risposta, solo dicendo che funziona per me quindi immagino sia un problema di configurazione o qualcosa del genere - ma ho pensato che fosse qualcosa che gli altri potrebbero trovare a portata di mano. Dovrebbe essere un commento ma per ragioni tecniche devo renderlo una risposta)

Non avevo incasinato la lezione di robot e ho appena passato un DIVERTIMENTO mezz'ora a fare casino e ad aggiungere qualche roba in cima a questa fresca classe java .

Per me inviare slash e backslash funzionano bene. Dal momento che il VK _ ??? roba funziona piuttosto bene con i caratteri ASCII, puoi inviare '\' o '/' e dovrebbe funzionare anche.

Ho usato Groovy perché è quello che gioco in questi giorni, ma ecco un bell'esempio e un mucchio di codice riutilizzabile che ho appena creato. È scritto come uno script, ma potrebbe facilmente essere convertito in una classe in Groovy o Java (e lo farò presto).

Questo deve essere eseguito da una shell "Priviliged" (ad esempio, fare clic con il tasto destro del mouse sul prompt dei comandi e selezionare "Esegui come amministratore").

inoltre DEVE avere il tempo di lasciar andare la tastiera! (Imparato così nel modo più duro), quindi se usi groovyShell e usi alt-r per eseguirlo, assicurati di mettere un ritardo di 1 secondo prima di inviare i primi tasti o il tuo ALT diventerà parte dei tasti premuti.

 
import java.awt.* 
import java.awt.event.* 
import static java.awt.event.KeyEvent.* 

r=new Robot() 
r.autoWaitForIdle = true 
r.autoDelay=200 // Usually works with 0 but sometimes that's too fast. 

// This will alt-tab you to your "Previous" app. While testing I edited this in notepad++ 
// then tabbed out to a shell to execute it, this tabbed back into my editor and typed 
// the "test" text. 
alt VK_TAB 

send "backslash=\\ \nforward slash =/" 

// This will send any string 
def send(String s) 
{ 
    def difference = ("a" as Character) - ("A" as Character) 
    s.each { 
     Character c=it as Character 
     if(c.isUpperCase()) { 
      shift c 
     } else if(c.isLowerCase()) { 
      send(c - difference) 
     } 
     else send(c) 
    } 
} 

// These will work for integers and chars, NOT strings 
def send(key) 
{ 
    press(key as Integer) 
    release(key as Integer) 
} 
def alt(key) 
{ 
    press VK_ALT 
    send key 
    release VK_ALT 
} 
def shift(key) 
{ 
    press VK_SHIFT 
    send key 
    release VK_SHIFT 
} 

def press(key) 
{ 
    r.keyPress(key as Integer) 
} 
def release(int key) 
{ 
    r.keyRelease(key as Integer) 
} 
Problemi correlati