问题
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