且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-18 12:47:58

正如其他人提到的,您需要使用 JNA 才能连接到操作系统的本机 API.幸运的是,有一个很棒的库可以做到这一点jnativehook.

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);
    }
}

使用Swing 使用提到的库.