Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: Regarding Keystrokes

  1. #1
    Junior Member
    Join Date
    May 2011
    Posts
    16
    My Mood
    Depressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Regarding Keystrokes

    Hi all,

    I'm working on a project that makes a keystroke program. Currently I have some questions, hopefully I'll be able to get some help here.


    When I click on the start button, I need to read/capture a .txt file (that consists the keystroke keys e.g KeyEvent.VK_TAB) using java, then run the keystroke event straight.

    Is it possible to be done?

    Thank You


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Regarding Keystrokes

    Pure Java can only capture keystroke events which are sent to a Java window/component (more specifically, windows that that JVM owns, not any JVM running). Keystrokes which are dispatched to other processes will not be received by Java, and there's no way to "monitor" Java for which keys are currently being pressed (which is kind of stupid since you can monitor the mouse pointer for current location and what buttons are being pressed).

    If you want to capture keystrokes outside of a Java window, you'll need to use JNI and write native code to intercept those messages.

    Dispatching of virtual keystrokes and/or mouse pointer actions can be done using the Robot class.

  3. #3
    Junior Member
    Join Date
    May 2011
    Posts
    16
    My Mood
    Depressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Regarding Keystrokes

    Thanks for the reply. May I ask if there is any examples on Keystroke in String? Cause what I have now is Keystroke in integers.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Regarding Keystrokes

    if there is any examples on Keystroke in String? Cause what I have now is Keystroke in integers.
    Please explain this in some more detail.
    What is the relationship between the KeyStroke class and the String class you are looking for?
    How do integers relate to the KeyStroke class?

  5. #5
    Junior Member
    Join Date
    May 2011
    Posts
    16
    My Mood
    Depressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Regarding Keystrokes

    I got this codings off the internet, and now I'm trying to implement it. because this keystroke is hardcoded, I wish to make it run with customised commands.

    What I want to do:

    Launch the program, allow users to customise the key strokes
    ,
    then save the file as a .txt file.

    After saving the file, users can click on the start button and the program will read the specific text file and run the keystrokes.

    I have problem doing so because the keystroke below runs in int array. However, if I were to read from a txt file, it will be a string. I won't be able to read the file in string and convert it to int. So I'm wondering if there is any ways to do it.

    I've added the codings that I've implemented and the codings that I found from the Internet. I hope this helps everyone. Hope you guys can help me! Thank you!

    //Implemented codings 
    import javax.swing.JFrame;
    import javax.swing.JMenuBar;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JButton;
    import javax.swing.JEditorPane;
    import javax.swing.JFileChooser;
    import javax.swing.JTextArea;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JPanel;
     
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.*;
    import java.io.*;
     
    import java.util.Scanner;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.BufferedWriter;
     
    import java.util.List;
    import java.util.ArrayList;
     
    public class JavaIDE extends JFrame implements ActionListener
    {
    	JMenuBar menu = new JMenuBar();
    	JMenu file = new JMenu("File");
    	JMenuItem file_open = new JMenuItem("Open");
    	JMenuItem file_save = new JMenuItem("Save");
    	JMenuItem file_close = new JMenuItem("Close");
    	JTextArea canvas = new JTextArea(10,20);
    	JScrollPane sp = new JScrollPane();
     
    	Robot r;
     
    	List<String> wordList = new ArrayList<String>();
     
    	public JavaIDE()
    	{
    		setSize(400, 400);
    		setTitle("Java IDE");
    		setJMenuBar(menu);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		//JMenu/Bar
    		file.add(file_open);
    		file.add(file_save);
    		file.add(file_close);
    		file_open.addActionListener(this);
    		file_save.addActionListener(this);
    		file_close.addActionListener(this);
     
    		menu.add(file);
     
        JPanel p1 = new JPanel();
    	 JScrollPane sp = new JScrollPane(canvas);
    	 sp = new JScrollPane(canvas, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    	 //canvas.setEditable(false);
    	 p1.add(sp);
     
        JButton btn1 = new JButton("Enter");
        btn1.addActionListener(this);
        btn1.setActionCommand("Enter");
     
        JButton btn2 = new JButton("Tab");
        btn2.addActionListener(this);
        btn2.setActionCommand("Tab");
     
        JButton btn3 = new JButton("Space");
        btn3.addActionListener(this);
        btn3.setActionCommand("Space");
     
        JButton btn4 = new JButton("Up");
        btn4.addActionListener(this);
        btn4.setActionCommand("Up");
     
        JButton btn5 = new JButton("Down");
        btn5.addActionListener(this);
        btn5.setActionCommand("Down");
     
         JButton btn6 = new JButton("Clear Contents");
        btn6.addActionListener(this);
        btn6.setActionCommand("Clear");
     
         JButton btn7 = new JButton("Start");
        btn7.addActionListener(this);
        btn7.setActionCommand("Start");
     
     
        JPanel p = new JPanel();
    	p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
     
        p.add(btn1);
        p.add(btn2);
        p.add(btn3);
        p.add(btn4);
        p.add(btn5);
        p.add(btn6);
        p.add(btn7);
     
    	setVisible(true);
        getContentPane().add(p, BorderLayout.WEST);
        getContentPane().add(new JScrollPane(canvas), BorderLayout.CENTER);
    	}
     
    	public void actionPerformed(ActionEvent e)
    	{
    		    String cmd = e.getActionCommand();
     
    	    if (cmd.equals("Enter")){
    	      canvas.append("KeyEvent.VK_ENTER; \n");
    	    }
    	    if (cmd.equals("Tab")){
    	      canvas.append("KeyEvent.VK_TAB; \n");
    	    }
    	    if (cmd.equals("Space")){
    	      canvas.append("KeyEvent.VK_SPACE; \n");
    	    }
    		if (cmd.equals("Up")){
    	      canvas.append("KeyEvent.VK_UP; \n");
    	    }
    		if (cmd.equals("Down")){
    	      canvas.append("KeyEvent.VK_DOWN; \n");
    	    }
    	    if (cmd.equals("Clear")){
    	      canvas.setText("");
    	    }
    	    if (cmd.equals("Start"))
    	    {
        		//clear application
     String browserPath = "C:/Program Files/Internet Explorer/iexplore";
                String url =  "C:\\Users\\ifcdu1\\Desktop\\Absences.html";
     
     
    String file_name = "C:/Users/ifcdu1/Desktop/keylogger.txt";
    wordList.add( file_name );
     
                 	try {
                     		String[] b = {browserPath,url};
                     		Runtime.getRuntime().exec(b);
     
    					List<String> wordList = new ArrayList<String>();
     
    					BufferedReader br = null;
    					br = new BufferedReader( new FileReader( "C:/Users/ifcdu1/Desktop/keylogger.txt" ) );
    					String word;
    					while( ( word = br.readLine() ) != null )
    					wordList.add( word );
     
    					 int aInt = Integer.parseInt(word);
     
    					 System.out.println(aInt);
     
     
    					int[] words = new int[ wordList.size() ];
    				//	wordList.toArray( words );
     
    	             for (int i = 0; i < words.length; i++)  sendKey(words[i]);
    	         // send mouse event to exit notepad
    	        // sendMouseClick(55, 74);     // File
    	         //sendMouseClick(50, 260);    // Exit
    	        // sendKey(KeyEvent.VK_TAB);   // Don't save
    	        // sendKey(KeyEvent.VK_ENTER);
    	      } catch (java.io.IOException ex) {
    	         ex.printStackTrace();   // for Run	time.exec()
    	      }
        	}
     
    		if(e.getSource().equals(file_open))
    		{
    			JFileChooser open = new JFileChooser();
    			int option = open.showOpenDialog(this);
    			if(option == JFileChooser.APPROVE_OPTION)
    			{
    				try
    				{
    					Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
    					String temp = "";
    					while(scan.hasNext())
    					{
    						temp += (scan.nextLine() + "\n");
    					}
    					canvas.setText(temp);
    					canvas.setEditable(true);
    				}
    				catch(Exception ex){}
    			}
    		}
     
    		if(e.getSource().equals(file_save))
    		{
    			JFileChooser save = new JFileChooser();
    			int option = save.showSaveDialog(this);
    			if(option == JFileChooser.APPROVE_OPTION)
    			{
    				try
    				{
    					BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
    					out.write(canvas.getText());
    					out.close();
    				}
    				catch(Exception ex){}
    			}
    		}
     
    		if(e.getSource().equals(file_close))
    		{
    			this.dispose();
    			System.out.println("close");
    		}
    	}
     
    private void sendKey(int keyCode) {
     
      	    r.keyPress(keyCode);
          r.keyRelease(keyCode);
          r.delay(100);   // for you to see the keystroke
       }
    	public static void main(String[] args)
    	{
    		 SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                new JavaIDE();
             }
          });
    	}
    }
    //CODE FROM INTERNET
    // Launch notepad, send key strokes, then send mouse events to exit.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    public class RobotDemoKeyAndMouse extends JFrame implements ActionListener {
     
       Robot r;
     
       RobotDemoKeyAndMouse () {   // constructor
          Container cp = getContentPane();
          cp.setLayout(new FlowLayout());
          Button btn = new Button("Start");
          btn.addActionListener(this);
          cp.add(btn);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setTitle("java.awt.Robot Demo");
          setSize(200, 100);
          setVisible(true);
       }
     
       public void actionPerformed (ActionEvent e) {  // for "start" button
          try {
             Runtime.getRuntime().exec("notepad.exe");  // launch notepad
             r = new Robot();
             r.delay(1000);       // wait for notepad to launch
     
             int [] keys = {
                KeyEvent.VK_T,
                KeyEvent.VK_E,
                KeyEvent.VK_S,
                KeyEvent.VK_T,
                KeyEvent.VK_ENTER
             };
             for (int i = 0; i < keys.length; i++)  sendKey(keys[i]);
             // send mouse event to exit notepad
             sendMouseClick(55, 74);     // File
             sendMouseClick(50, 260);    // Exit
             sendKey(KeyEvent.VK_TAB);   // Don't save
             sendKey(KeyEvent.VK_ENTER);
          } catch (java.io.IOException ex) {
             ex.printStackTrace();   // for Runtime.exec()
          } catch (AWTException ex) {
             ex.printStackTrace();   // for Robot()
          }
       }
     
       private void sendKey(int keyCode) {
          r.keyPress(keyCode);
          r.keyRelease(keyCode);
          r.delay(500);   // for you to see the keystroke
       }
     
       private void sendMouseClick(int x, int y) {
          r.mouseMove(x, y);
          r.delay(1000);   // for you to see the move
          r.mousePress(InputEvent.BUTTON1_MASK);
          r.mouseRelease(InputEvent.BUTTON1_MASK);
       }
     
       public static void main (String [] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                new RobotDemoKeyAndMouse ();
             }
          });
       }
    }

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Regarding Keystrokes

    I have problem doing so because the keystroke below runs in int array
    You can read data from a txt file as ints. See the Scanner class's nextInt method.
    Or you can convert String to int by using the Integer class's parseInt method.

  7. #7
    Junior Member
    Join Date
    May 2011
    Posts
    16
    My Mood
    Depressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Regarding Keystrokes

    Quote Originally Posted by Norm View Post
    You can read data from a txt file as ints. See the Scanner class's nextInt method.
    Or you can convert String to int by using the Integer class's parseInt method.
    If my saved txt file is like below, I can still read them as integers?

    KeyEvent.VK_ENTER;
    KeyEvent.VK_TAB;
    KeyEvent.VK_SPACE;
    KeyEvent.VK_UP;
    KeyEvent.VK_DOWN;
    KeyEvent.VK_ENTER;
    KeyEvent.VK_TAB;
    KeyEvent.VK_SPACE;
    KeyEvent.VK_UP;
    KeyEvent.VK_DOWN;

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Regarding Keystrokes

    What you show appears to be text. It would be read as a String, not as int.

    In a compiled java program, KeyEvent.VK_UP etc are int.

  9. #9
    Junior Member
    Join Date
    May 2011
    Posts
    16
    My Mood
    Depressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Regarding Keystrokes

    Which means to say this method is not workable? If thats the case, is there any way I can do to make it work?

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Regarding Keystrokes

    way I can do to make it work
    You need to define what you want to do. What do you want the data in the file to tell you? When you read the file, what actions will you take?

  11. #11
    Junior Member
    Join Date
    May 2011
    Posts
    16
    My Mood
    Depressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Regarding Keystrokes

    I need to make a Keystroke program that allows users to customise the way they want the commands to work. This customised data will then be saved as txt file, then the program will read the datas and run the KeyEvent on a website.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Regarding Keystrokes

    I can't recommend anymore than I said before:
    What do you want the data in the file to tell you? When you read the file, what actions will you take?

    Start at the end, what do you want to do with the contents of the file? Then figure out how to read the data from the file that will enable you to do that. Then figure out how to write the data to the file.
    Perhaps you'll need a Map to convert the contents of the file (the key) to the int (the value) you need.
    Or you could write the KeyStroke name followed by the int value to the file: VK_UP(38). When reading the file, convert the "38" to an int.
    Last edited by Norm; May 24th, 2011 at 09:24 PM.

  13. #13
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Regarding Keystrokes

    It may be possible to achieve a crude implementation with Java, but Java really isn't the right tool for the job. You'd be far better off using a native language that gives direct access to the OS facilities, so, for example, your keystroke program could run in the background as a service and intercept the OS key handling via native APIs.

    To a man with a hammer, everything looks like a nail...