I am writing code that opens notepad, but when I want to write an exclamation mark it throws an error; here is the code I am using to write the exclamation mark.

robot.keyPress(KeyEvent.VK_EXCLAMATION_MARK);
 robot.keyRelease(KeyEvent.VK_EXCLAMATION_MARK);

Why is it giving me the error?

Edited 5 Years Ago by sirlink99: n/a

This is the error

Exception in thread "main" java.lang.IllegalArgumentException: Invalid key code
	at sun.awt.windows.WRobotPeer.keyPress(Native Method)
	at java.awt.Robot.keyPress(Unknown Source)
	at test2.Frame.<init>(Frame.java:68)
	at test2.Frame.main(Frame.java:83)

and the code looks like this

package test2;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
public class Frame {

	Frame (){
		 try {
	            
	            Robot robot = new Robot();
	            // Creates the delay of 2 sec so that it can open notepad before
	            // Robot start writting
				Runtime.getRuntime().exec("notepad");
	            robot.delay(2000);
	            robot.keyPress(KeyEvent.VK_H);
	            robot.keyRelease(KeyEvent.VK_H);
	            robot.keyPress(KeyEvent.VK_I);
	            robot.keyRelease(KeyEvent.VK_I);
	            robot.keyPress(KeyEvent.VK_EXCLAMATION_MARK);
	            robot.keyRelease(KeyEvent.VK_EXCLAMATION_MARK);
	            
	        } catch (AWTException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Frame f = new Frame ();
	}

}

This is just a guess, but anyway...
depending on your keyboard layout, there probably isn't a key that has ! as its primary meaning. For example, on my UK keyboard I have to:
press VK_Shift, press VK_1, release VK_1, release VK_Shift

This article has been dead for over six months. Start a new discussion instead.