简体   繁体   English

检测是否有任何鼠标按钮被按下,如果是,是哪一个?

[英]Detect if any mouse button is being pressed, and if so, which one?

Basically, I want to query if any mouse button is being pressed and if so, which one.基本上,我想查询是否按下了任何鼠标按钮,如果是,是哪一个。 The problem is that I don't use a (constantly focused) UI environment.问题是我不使用(持续关注的)UI 环境。 It is meant to be able to run in the background while the OS is focused on another window.它旨在能够在操作系统专注于另一个 window 时在后台运行。 I just have a Swing GUI set up for easy controlling.我只设置了一个 Swing GUI 以便于控制。

How could I do this?我怎么能这样做?

(By the way, I am trying to query it inside of a loop, so setting up an event listener wouldn't be efficient.) (顺便说一句,我试图在循环中查询它,因此设置事件侦听器效率不高。)

As mentioned by others you would need to use JNA in order to hook into the operating systems native APIs.正如其他人所提到的,您需要使用 JNA 才能连接到操作系统的原生 API。 Lucky for you there is a great library that does just that jnativehook .幸运的是,有一个很棒的库可以做到jnativehook

Here is some demo code which creates a Global Mouse Listener :这是一些创建全局鼠标侦听器的演示代码:

import GlobalScreen;
import NativeHookException;
import NativeMouseEvent;
import NativeMouseInputListener;

public class GlobalMouseListenerExample implements NativeMouseInputListener {
    public void nativeMouseClicked(NativeMouseEvent e) {
        System.out.println("Mouse Clicked: " + e.getClickCount());
    }

    public void nativeMousePressed(NativeMouseEvent e) {
        System.out.println("Mouse Pressed: " + e.getButton());
    }

    public void nativeMouseReleased(NativeMouseEvent e) {
        System.out.println("Mouse Released: " + e.getButton());
    }

    public void nativeMouseMoved(NativeMouseEvent e) {
        System.out.println("Mouse Moved: " + e.getX() + ", " + e.getY());
    }

    public void nativeMouseDragged(NativeMouseEvent e) {
        System.out.println("Mouse Dragged: " + e.getX() + ", " + e.getY());
    }

    public static void main(String[] args) {
        try {
            GlobalScreen.registerNativeHook();
        }
        catch (NativeHookException ex) {
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());

            System.exit(1);
        }

        // Construct the example object.
        GlobalMouseListenerExample example = new GlobalMouseListenerExample();

        // Add the appropriate listeners.
        GlobalScreen.addNativeMouseListener(example);
        GlobalScreen.addNativeMouseMotionListener(example);
    }
}

Also don't forget to read about thread safety when Working with Swing using the library mentioned.在使用提到的库使用 Swing时,不要忘记阅读有关线程安全的信息。

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

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