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

南楼画角 提交于 2021-02-19 07:39:31

问题


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. It is meant to be able to run in the background while the OS is focused on another window. I just have a Swing GUI set up for easy controlling.

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.)


回答1:


As mentioned by others you would need to use JNA in order to hook into the operating systems native APIs. Lucky for you there is a great library that does just that 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.



来源:https://stackoverflow.com/questions/65346235/detect-if-any-mouse-button-is-being-pressed-and-if-so-which-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!