基本上,我想查询是否有鼠标按钮被按下,如果是,是哪一个。问题是我没有使用(持续关注的(UI环境。这意味着当操作系统专注于另一个窗口时,它可以在后台运行。我只是设置了一个Swing GUI以便于控制。
我怎么能这么做?
(顺便说一句,我试图在循环中查询它,所以设置事件侦听器效率不高。(
正如其他人所提到的,您需要使用JNA才能挂接到操作系统的本机API中。幸运的是,有一个伟大的图书馆正是这样做的。
以下是一些创建全局鼠标侦听器的演示代码:
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时,不要忘记阅读有关线程安全的内容。