JNA鼠标钩子的工作示例

发布于 2024-09-16 11:53:51 字数 77 浏览 4 评论 0原文

谁能给我提供一个 JNA 鼠标钩子的工作示例,它能够在我的 Java Swing 应用程序之外跟踪鼠标移动/单击?

提前致谢

Can any one provide me with a working example of JNA mouse hook, which would be able to track mouse movements/click outside my Java Swing application ?

Thanks in Advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

檐上三寸雪 2024-09-23 11:53:51

是的,这是代码...

public class CWMouseHook {
public final User32 USER32INST;
public final Kernel32 KERNEL32INST;
public CWMouseHook()
{
    if(!Platform.isWindows())
    {
        throw new UnsupportedOperationException("Not supported on this platform.");
    }
    USER32INST = User32.INSTANCE;
    KERNEL32INST = Kernel32.INSTANCE;
    mouseHook=hookTheMouse();
    Native.setProtected(true);

}
public static LowLevelMouseProc mouseHook;
public HHOOK hhk;
public Thread thrd;
public boolean threadFinish = true;
public boolean isHooked = false;
public static final int WM_MOUSEMOVE = 512;
public static final int WM_LBUTTONDOWN = 513;
public static final int WM_LBUTTONUP = 514;
public static final int WM_RBUTTONDOWN = 516;
public static final int WM_RBUTTONUP = 517;
public static final int WM_MBUTTONDOWN = 519;
public static final int WM_MBUTTONUP = 520;


public void unsetMouseHook()
{
    threadFinish = true;
    if (thrd.isAlive())
    {
        thrd.interrupt();
        thrd = null;
    }
    isHooked = false;
}
public boolean isIsHooked()
{
    return isHooked;
}
public void setMouseHook()
{
    thrd = new Thread(new Runnable() {
        @Override
        public void run()
            {
                  try
                  {
                        if(!isHooked)
                        {   
                            hhk = USER32INST.SetWindowsHookEx(14, mouseHook,KERNEL32INST.GetModuleHandle(null),0);
                            isHooked = true;
                            MSG msg = new MSG();
                            while ((USER32INST.GetMessage(msg, null, 0, 0)) != 0)
                            {
                                USER32INST.TranslateMessage(msg);     
                                USER32INST.DispatchMessage(msg);
                                System.out.print(isHooked);
                                if (!isHooked)
                                      break;
                            }
                        }
                        else
                            System.out.println("The Hook is already installed.");
                }
                catch (Exception e)
                {   System.err.println(e.getMessage());
                    System.err.println("Caught exception in MouseHook!");
                }
        }
    },"Named thread");
    threadFinish = false;
    thrd.start();

}
private interface LowLevelMouseProc extends HOOKPROC
{
    LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT lParam);
}
public LowLevelMouseProc hookTheMouse() {
    return new LowLevelMouseProc()
    {
        @Override
        public LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT info) {
            if (nCode >= 0)
            {
                switch(wParam.intValue())
                {
                    case CWMouseHook.WM_LBUTTONDOWN:
                        // do stuff
                        break;
                    case CWMouseHook.WM_RBUTTONDOWN:
                        //do stuff
                        break;
                    case CWMouseHook.WM_MBUTTONDOWN:
                        //do other stuff
                        break;
                    case CWMouseHook.WM_LBUTTONUP:
                         //do even more stuff
                         break;
                    case CWMouseHook.WM_MOUSEMOVE:

                        break;                         
                    default:
                        break;
                }
                 /****************************DO NOT CHANGE, this code unhooks mouse *********************************/
                 if (threadFinish == true)
                  {                      
                     USER32INST.PostQuitMessage(0);
                  }
                /***************************END OF UNCHANGABLE *******************************************************/
            }
            return USER32INST.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
        }
    };
}
public class Point extends Structure
{
    public class ByReference extends Point implements Structure.ByReference {};
    public NativeLong x;
    public NativeLong y;
}
public static class MOUSEHOOKSTRUCT extends Structure
{
    public static class ByReference extends MOUSEHOOKSTRUCT implements Structure.ByReference {};
    public POINT pt;
    public HWND hwnd;
    public int wHitTestCode;
    public ULONG_PTR dwExtraInfo;
}

这就是全部内容。干杯。
这基本上是抄袭 Sun 论坛中一个人的代码...但也经过我的测试,它的工作原理再次令人欢呼。

编辑:我编辑了代码,使其包含 LowLevelMouseProc,但您可以使用您可以在其他地方定义的 HOOK 扩展。没关系。请注意,由于某种原因,您必须将变量 mouseHook 设置为静态,否则钩子会在一段时间后取消钩子。

Yep, here is the code...

public class CWMouseHook {
public final User32 USER32INST;
public final Kernel32 KERNEL32INST;
public CWMouseHook()
{
    if(!Platform.isWindows())
    {
        throw new UnsupportedOperationException("Not supported on this platform.");
    }
    USER32INST = User32.INSTANCE;
    KERNEL32INST = Kernel32.INSTANCE;
    mouseHook=hookTheMouse();
    Native.setProtected(true);

}
public static LowLevelMouseProc mouseHook;
public HHOOK hhk;
public Thread thrd;
public boolean threadFinish = true;
public boolean isHooked = false;
public static final int WM_MOUSEMOVE = 512;
public static final int WM_LBUTTONDOWN = 513;
public static final int WM_LBUTTONUP = 514;
public static final int WM_RBUTTONDOWN = 516;
public static final int WM_RBUTTONUP = 517;
public static final int WM_MBUTTONDOWN = 519;
public static final int WM_MBUTTONUP = 520;


public void unsetMouseHook()
{
    threadFinish = true;
    if (thrd.isAlive())
    {
        thrd.interrupt();
        thrd = null;
    }
    isHooked = false;
}
public boolean isIsHooked()
{
    return isHooked;
}
public void setMouseHook()
{
    thrd = new Thread(new Runnable() {
        @Override
        public void run()
            {
                  try
                  {
                        if(!isHooked)
                        {   
                            hhk = USER32INST.SetWindowsHookEx(14, mouseHook,KERNEL32INST.GetModuleHandle(null),0);
                            isHooked = true;
                            MSG msg = new MSG();
                            while ((USER32INST.GetMessage(msg, null, 0, 0)) != 0)
                            {
                                USER32INST.TranslateMessage(msg);     
                                USER32INST.DispatchMessage(msg);
                                System.out.print(isHooked);
                                if (!isHooked)
                                      break;
                            }
                        }
                        else
                            System.out.println("The Hook is already installed.");
                }
                catch (Exception e)
                {   System.err.println(e.getMessage());
                    System.err.println("Caught exception in MouseHook!");
                }
        }
    },"Named thread");
    threadFinish = false;
    thrd.start();

}
private interface LowLevelMouseProc extends HOOKPROC
{
    LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT lParam);
}
public LowLevelMouseProc hookTheMouse() {
    return new LowLevelMouseProc()
    {
        @Override
        public LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT info) {
            if (nCode >= 0)
            {
                switch(wParam.intValue())
                {
                    case CWMouseHook.WM_LBUTTONDOWN:
                        // do stuff
                        break;
                    case CWMouseHook.WM_RBUTTONDOWN:
                        //do stuff
                        break;
                    case CWMouseHook.WM_MBUTTONDOWN:
                        //do other stuff
                        break;
                    case CWMouseHook.WM_LBUTTONUP:
                         //do even more stuff
                         break;
                    case CWMouseHook.WM_MOUSEMOVE:

                        break;                         
                    default:
                        break;
                }
                 /****************************DO NOT CHANGE, this code unhooks mouse *********************************/
                 if (threadFinish == true)
                  {                      
                     USER32INST.PostQuitMessage(0);
                  }
                /***************************END OF UNCHANGABLE *******************************************************/
            }
            return USER32INST.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
        }
    };
}
public class Point extends Structure
{
    public class ByReference extends Point implements Structure.ByReference {};
    public NativeLong x;
    public NativeLong y;
}
public static class MOUSEHOOKSTRUCT extends Structure
{
    public static class ByReference extends MOUSEHOOKSTRUCT implements Structure.ByReference {};
    public POINT pt;
    public HWND hwnd;
    public int wHitTestCode;
    public ULONG_PTR dwExtraInfo;
}

That's all about there is to it. Cheers.
It's a basically a ripoff of the code of a guy in Sun forums...but also tested by me, and it works so cheers again.

Edit: I edited the code so it includes the LowLevelMouseProc but you can use your extension of HOOK which you can define elsewhere. It doesn't matter that much. Be wary that for some reason you have TO have the variable mouseHook as static otherwise hook just unhooks after a while.

终弃我 2024-09-23 11:53:51

动作:

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseWheelEvent;
import org.jnativehook.mouse.NativeMouseWheelListener;

public class GlobalMouseWheelListenerExample implements NativeMouseWheelListener {
    public void nativeMouseWheelMoved(NativeMouseWheelEvent e) {
        System.out.println("Mosue Wheel Moved: " + e.getWheelRotation());
    }

    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());
            ex.printStackTrace();

            System.exit(1);
        }

        // Construct the example object and initialze native hook.
        GlobalScreen.getInstance().addNativeMouseWheelListener(new GlobalMouseWheelListenerExample());
    }
}

点击:

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;

public class GlobalMouseListenerExample implements NativeMouseInputListener {
        public void nativeMouseClicked(NativeMouseEvent e) {
                System.out.println("Mosue Clicked: " + e.getClickCount());
        }

        public void nativeMousePressed(NativeMouseEvent e) {
                System.out.println("Mosue Pressed: " + e.getButton());
        }

        public void nativeMouseReleased(NativeMouseEvent e) {
                System.out.println("Mosue Released: " + e.getButton());
        }

        public void nativeMouseMoved(NativeMouseEvent e) {
                System.out.println("Mosue Moved: " + e.getX() + ", " + e.getY());
        }

        public void nativeMouseDragged(NativeMouseEvent e) {
                System.out.println("Mosue 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 for the example object.
                GlobalScreen.getInstance().addNativeMouseListener(example);
                GlobalScreen.getInstance().addNativeMouseMotionListener(example);
        }
}

movements:

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseWheelEvent;
import org.jnativehook.mouse.NativeMouseWheelListener;

public class GlobalMouseWheelListenerExample implements NativeMouseWheelListener {
    public void nativeMouseWheelMoved(NativeMouseWheelEvent e) {
        System.out.println("Mosue Wheel Moved: " + e.getWheelRotation());
    }

    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());
            ex.printStackTrace();

            System.exit(1);
        }

        // Construct the example object and initialze native hook.
        GlobalScreen.getInstance().addNativeMouseWheelListener(new GlobalMouseWheelListenerExample());
    }
}

click:

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;

public class GlobalMouseListenerExample implements NativeMouseInputListener {
        public void nativeMouseClicked(NativeMouseEvent e) {
                System.out.println("Mosue Clicked: " + e.getClickCount());
        }

        public void nativeMousePressed(NativeMouseEvent e) {
                System.out.println("Mosue Pressed: " + e.getButton());
        }

        public void nativeMouseReleased(NativeMouseEvent e) {
                System.out.println("Mosue Released: " + e.getButton());
        }

        public void nativeMouseMoved(NativeMouseEvent e) {
                System.out.println("Mosue Moved: " + e.getX() + ", " + e.getY());
        }

        public void nativeMouseDragged(NativeMouseEvent e) {
                System.out.println("Mosue 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 for the example object.
                GlobalScreen.getInstance().addNativeMouseListener(example);
                GlobalScreen.getInstance().addNativeMouseMotionListener(example);
        }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文