Mostafa Jamareh
Mostafa Jamareh

Reputation: 1439

Can i use java to capture keyboard and mouse event in background?

I want to write an application that runs in the background and waits for the user to press a key in any other application. When the key is pressed, my application will do something.

Is this possible in Java? If so, how can this be accomplished?

Upvotes: 5

Views: 12188

Answers (7)

Dheeraj Upadhyay
Dheeraj Upadhyay

Reputation: 328

Yes, you can do in java

add the below dependency in pom.xml or add jnativehook-2.0.2.jar in your classpath

<dependency>
        <groupId>com.1stleg</groupId>
        <artifactId>jnativehook</artifactId>
        <version>2.0.2</version>
    </dependency>

then create a class

package main.java.com.spring.demo.test;

/*use JNativeHook here is an example that prints every key and the number of 
      keys 
     pressed, you could modify this to your needs :-
  */
 import org.jnativehook.GlobalScreen;
 import org.jnativehook.keyboard.NativeKeyEvent;
 import org.jnativehook.keyboard.NativeKeyListener;

 public class BackgroundKeyStroke implements NativeKeyListener {
      public static void main(String[] args) {
         try {
            GlobalScreen.registerNativeHook();
         } catch (Exception e) {
            e.printStackTrace();
         }

      GlobalScreen.addNativeKeyListener(new BackgroundKeyStroke());
     }

     public void nativeKeyPressed(NativeKeyEvent e) {
      //do your operation here below is demo
      System.out.println("Pressed :" + 
        NativeKeyEvent.getKeyText(e.getKeyCode()));
     }

     public void nativeKeyReleased(NativeKeyEvent e) {
        // TODO Auto-generated method stub

     }

     public void nativeKeyTyped(NativeKeyEvent e) {
        // TODO Auto-generated method stub

     }
  }

Upvotes: 0

S. Alcic
S. Alcic

Reputation: 81

JNativeHook provides a Java-based API for native keyboard and mouse event hooks.

Upvotes: 4

Dave Jarvis
Dave Jarvis

Reputation: 31191

As others have mentioned, use JNativeHook. Here's a short example:

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import java.util.concurrent.CountDownLatch;

import static java.util.logging.Level.OFF;
import static java.util.logging.Logger.getLogger;
import static org.jnativehook.GlobalScreen.*;
import static org.jnativehook.keyboard.NativeKeyEvent.getKeyText;

public class Harness implements NativeKeyListener {
  // Terminate after 100 keystrokes.
  private final CountDownLatch mLatch = new CountDownLatch( 100 );

  @Override
  public void nativeKeyPressed( final NativeKeyEvent e ) {
    System.out.println( "Pressed: " + getKeyText( e.getKeyCode() ) );
    mLatch.countDown();
  }

  @Override
  public void nativeKeyReleased( final NativeKeyEvent e ) {
    System.out.println( "Released: " + getKeyText( e.getKeyCode() ) );
  }

  @Override
  public void nativeKeyTyped( final NativeKeyEvent e ) {
    System.out.println( "Typed: " + e );
  }

  private void start() throws InterruptedException {
    System.out.println("Awaiting keyboard events.");
    mLatch.await();
    System.out.println("All keyboard events have fired, exiting.");
  }

  public static void main( final String[] args )
      throws NativeHookException, InterruptedException {
    disableNativeHookLogger();
    registerNativeHook();

    final var harness = new Harness();
    addNativeKeyListener( harness );

    System.out.println( "Listener attached.");
    harness.start();

    System.out.println( "Listener detached.");
    removeNativeKeyListener( harness );
  }

  private static void disableNativeHookLogger() {
    final var logger = getLogger( GlobalScreen.class.getPackage().getName() );
    logger.setLevel( OFF );
    logger.setUseParentHandlers( false );
  }
}

Upvotes: 0

Wanted to add information for the next people on Ip ziet post:

I don't remember exactly what he did, but he told me that he didn't have to use to much of native library, core java already has good support of OS event such as keyboard, screen, app, OS process..etc..

You can easily write KeyInput in java using java.awt.robot: https://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html Quick and easy to use. And without JNA.

But read is an other subject that require JNA. Looking for reading solution too. If I find a good read solution, it is going to be here: https://github.com/EloiStree/2020_02_09_OpenMacroInput/issues/26

Upvotes: 0

Artemkller545
Artemkller545

Reputation: 999

Yes, you can use JKeyMaster with JNA to capture keyboard input in background.

https://github.com/tulskiy/jkeymaster

    provider.register(KeyStroke.getKeyStroke("shift"), listener);

This will let listener know that shift was pressed.

For more information check the github docs.

Make sure your listener implements HotKeyListener

class SampleListener implements HotKeyListener {

    @Override
    public void onHotkey() {
        // do your things here
    }
}

Upvotes: 2

Xabster
Xabster

Reputation: 3720

In pure Java: no it is not possible.

You need a piece of native code to catch keyboard and mouse events when your application is not in focus.

Upvotes: 1

Ip ziet
Ip ziet

Reputation: 307

Just, it is possible. I saw my friend wrote a java program to help him play an online game when he went sleep... His java application was able to read some simple captcha...

I don't remember exactly what he did, but he told me that he didn't have to use to much of native library, core java already has good support of OS event such as keyboard, screen, app, OS process..etc..

Upvotes: -4

Related Questions