检测是否有任何鼠标按钮被按下,如果是,是哪个? [英] Detect if any mouse button is being pressed, and if so, which one?

查看:52
本文介绍了检测是否有任何鼠标按钮被按下,如果是,是哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想查询是否有任何鼠标按钮被按下,如果按下,是哪个按钮.问题是我不使用(不断聚焦的)UI 环境.它旨在能够在操作系统专注于另一个窗口时在后台运行.我只是设置了一个 Swing GUI 以便于控制.

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.

我怎么能这样做?

(顺便说一句,我试图在循环内查询它,因此设置事件侦听器效率不高.)

(By the way, I am trying to query it inside of a loop, so setting up an event listener wouldn't be efficient.)

推荐答案

正如其他人提到的,您需要使用 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 使用提到的库.

这篇关于检测是否有任何鼠标按钮被按下,如果是,是哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆