Is it possible to have a MouseMotionListener listen to all system mouse motion events?

不羁岁月 提交于 2019-12-01 17:41:45

You can subscribe to all mouse events within your Java container hierarchy using Toolkit.addAWTEventListener(AWTEventListener listener, long eventMask). The eventMask parameter determines which events the listener will receive.

So your code would look something like :

Toolkit.getDefaultToolkit().addAWTEventListener(new MyMouseMotionListener(), AWTEvent.MOUSE_MOTION_EVENT_MASK);

UPDATE: You could poll MouseInfo for position but you'll never get button state. You will need to use native code to get button state.

I do not think there is any way without using native code to listen to the mouse cursor outside of the cotainer hierarchy of your application.

Trucido

I solved the same issue by using the above mentioned ability to get the mouse position upon request. I then launched a new thread to do this continuously durring the rest of the programs execution.

MouseInfo.getPointerInfo().getLocation()

Also I had to make the main class extend Thread thus

public class MouseMotion extends Thread {

This requies you to make a function called run. In your void function simply create an infinite loop

public void run() {
int n=10;
for (int i=0;i<n; n++) //horrible infinite loop
{
    Thread.sleep(100); //this will slow the capture rate to 0.1 seconds
    PointerInfo a = MouseInfo.getPointerInfo();
    Point p = new Point (0,0);
    a = MouseInfo.getPointerInfo();
    p = a.getLocation();
    int x = (int)p.getX(); //getX and getY return doubles so typecast
    int y = (int)p.getY();
    System.out.println(""+x+"   "+y);   //to see it grabing locations not needed
}
}

All that is left now is to call the thread when you wana start watching your mouse motion. I start the thread right after my main as such

public static main (String[] args) throws Exception {
Thread thread = new MouseMotion();
thread.start();
...}

If you want to listen/capture all mouse events on the system (as in, not just your application window), you'll need a mouse hook.

There are a few libraries for this, one of which I use on a regular basis for applications.

JNativeHook has exceptional ability to handle both native mouse and keyboard events. (google it I am too lazy to go to the subversion. Although you can just download the library, and it works just like a regular mouse event after you make two calls to the library.

I wish when I was surfing google someone would have posted this library on a thread like this. I use stackoverflow all the time but I'm not a registered member, because I never ask for help publicly.

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