Question

I want to be able to end my program when a certain key is pressed (For this example we will say when k is pressed). I know that this could be done by using JFrame and KeyListener but want this my listener to run in the background. My program currently modifies word documents which means the active window would not be JFrame so it would no be recording the keys that are pressed. Also bufferd readers are not an option as previously mentioned, the java program that is running is not the selected window. I have spent many hours researching different ways however all I have found is ways to see if they mouse is pressed using AWTEvents

At the very worst case I will check to see if 2nd mouse button is pressed and end my code then, but ideally I would want to just end it on the key pressed. Any help would be great, comment for any clarification.

Was it helpful?

Solution

...I know that this could be done by using JFrame and KeyListener

No, you would almost never add a KeyListener to a JFrame, or use a KeyListener in general in Swing GUI's, even if you wanted to listen for keystrokes in an active GUI.

but want this my listener to run in the background.

Then you're looking for a key logger and will need to hook the keyboard input, something that cannot be done in plain vanilla core Java.

The easiest way that I do this is by using another language such as the AutoIt scripting language (if this is Windows), and then having my AutoIt notify my Java program via standard input and output sockets.

A more difficult solution (for me) is to use C or C++ to write your own keyboard hook, and then link this into Java via JNI or JNA. Regardless, any solution must be platform dependent.

OTHER TIPS

I agree with hovercraft here.. if it is possible, try to use AutoIt.. you may create a script that waits for a certain keypress, and just close your java program directly through AutoIt..

to detect the keypress, you may look into this page.. and to close your java program, you may use an automated click on the close button in your Java program's window.. look into this page..

hope it helps..

My suggesting would be to use Auto Hot Key to manage the java program:

Run java.exe MyClass ,,,javaPID
^!k::Process, Close, %javaPID%

This will start the program when it is run, and close it when you press Ctrl-Alt-K

if(new Scanner(new InputStreamReader(System.in)).nextLine().length()>0)
    {
        System.exit(0);
    }

You can use this to terminate your core java Pragram on key Press

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top