简体   繁体   English

我可以使用java在后台捕获键盘和鼠标事件吗?

[英]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?这在Java中可能吗? If so, how can this be accomplished?如果是这样,如何实现?

JNativeHook为本地键盘和鼠标事件挂钩提供了基于 Java 的 API。

Yes, you can use JKeyMaster with JNA to capture keyboard input in background.是的,您可以使用 JKeyMaster 和 JNA 在后台捕获键盘输入。

https://github.com/tulskiy/jkeymaster https://github.com/tulskiy/jkeymaster

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

This will let listener know that shift was pressed.这会让听众知道按下了shift

For more information check the github docs.有关更多信息,请查看 github 文档。

Make sure your listener implements HotKeyListener确保你的监听器实现HotKeyListener

class SampleListener implements HotKeyListener {

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

In pure Java: no it is not possible.在纯 Java 中:不,这是不可能的。

You need a piece of native code to catch keyboard and mouse events when your application is not in focus.当您的应用程序不在焦点时,您需要一段本机代码来捕获键盘和鼠标事件。

Wanted to add information for the next people on Ip ziet post:想在 Ip ziet 帖子上为下一个人添加信息:

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..我不记得他到底做了什么,但他告诉我他不必使用太多的原生库,核心 java 已经对键盘、屏幕、应用程序、操作系统进程等操作系统事件有很好的支持。 ..

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.您可以使用 java.awt.robot 在 java 中轻松编写 KeyInput: https ://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html 快速且易于使用。 And without JNA.并且没有 JNA。

But read is an other subject that require JNA.但是阅读是另一个需要 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如果我找到一个好的阅读解决方案,它将在这里: https ://github.com/EloiStree/2020_02_09_OpenMacroInput/issues/26

As others have mentioned, use JNativeHook.正如其他人提到的,使用 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 );
  }
}

Yes, you can do in java是的,你可以用java做

add the below dependency in pom.xml or add jnativehook-2.0.2.jar in your classpath在 pom.xml 中添加以下依赖项或在您的类路径中添加jnativehook-2.0.2.jar

<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

     }
  }

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...我看到我的朋友写了一个java程序来帮助他在睡觉时玩网络游戏......他的java应用程序能够读取一些简单的验证码......

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..我不记得他到底做了什么,但他告诉我他不必使用太多的原生库,核心 java 已经对键盘、屏幕、应用程序、操作系统进程等操作系统事件有很好的支持。 ..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM