views:

215

answers:

4

I would like to write a program which can monitor activity of my keyboard. In more details, the Java program should "see" which key is pressed/released and when. All this information should be stored in a given file.

First of all I would like to know if it's possible to do it with Java. I know that it's possible if I type in a text field generated by Java program. But is it possible for Java to monitor the keyboard activity if I type, let say, in a text field of a browser or, for example, in word (or open office) document?

A: 

It's likely possible to write a Java-based key logger using some native libraries, although be aware that such a program is likely more noticeable than one with a different technology, since the Java VM will need to be running for it to work. Keep that in mind if you're trying to be clandestine.

Also, if you just need such a program for use, and don't have to develop it yourself, there are many hardware and software keylogging systems already out there that you could use instead.

phoebus
A: 

I think that native functions can do it. It's something like you can connect c++ with Java.

http://en.wikipedia.org/wiki/Java_Native_Interface

oneat
+2  A: 

These events are directed to the window which has the focus, from all events on the desktop you can only get the mouse position.

import java.awt.MouseInfo;


    public class Mouse {
        public static void main(String[] args) {
            while ( true ) {
                System.out.println( MouseInfo.getPointerInfo().getLocation() );
            }
        }
    }

For capturing sysem wide (what you need for word) you need to include a native lib

Code example for windows: Native keyboard mouse hook

stacker
Maybe add just a little delay in that while loop :-)
rsp
A: 

What you are requesting is not possible using the Java API. In order to do system-wide key logging you need to register with win32 (or other OS native) hooks. Specifically, this will be done using native libraries and interfacing with the JNI.

There are some code snippets over at http://forums.sun.com/thread.jspa?messageID=3808163#3808163. It's a good example of how to get started with JNI and registering a Java callback to a win32 hook.

Yuval A