java - 检测鼠标单击屏幕上的任意位置 [英] java - Detect Mouse Clicks Anywhere On Screen

查看:123
本文介绍了java - 检测鼠标单击屏幕上的任意位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的应用能够在屏幕上的任何位置检测鼠标点击,而无需关注应用。我希望它能够普遍检测鼠标事件,即使它被最小化。到目前为止,我只能在摇摆gui中检测鼠标事件。

I want my app to detect mouse clicks anywhere on the screen without having to have the app focused. I want it to detect mouse events universally even if its minimized. So far I've only been able to detect mouse events within a swing gui.

Autohotkey可以随时检测鼠标点击并获取鼠标位置,我该怎么办这与java?

Autohotkey can detect mouse clicks and get the mouse's position at any time, how can I do this with java?

推荐答案

这可能是一个小技巧。应该是100%跨平台(在Linux和Windows上测试)。基本上,你创建一个小的JWindow,使它alwaysOnTop并用鼠标使用计时器移动它。

It is possible with a little trick. Should be 100% cross-platform (tested on Linux & Windows). Basically, you create a small JWindow, make it "alwaysOnTop" and move it around with the mouse using a timer.

然后,你可以记录点击,关闭窗口并使用Robot类将点击转发给实际的接收器。

Then, you can record the click, dismiss the window and forward the click to the actual receiver using the Robot class.

在我的测试中,左右键点击完全正常。

Short left and right clicks work completely fine in my tests.

你也可以模拟拖动和点击并保持,只是转发似乎更难。

You could also simulate dragging and click-and-hold, just forwarding that seems harder.

我有代码,但它在我的Java中扩展(JavaX)。 JavaX确实转换为Java源代码,因此您可以查看示例此处

I have code for this, but it is in my Java extension (JavaX). JavaX does translate into Java source code, so you can check out the example here.

JavaX中的代码:

The code in JavaX:

static int windowSize = 11; // odd should look nice. Set to 1 for an invisible window
static int clickDelay = 0; // Delay in ms between closing window and forwarding click. 0 seems to work fine.
static int trackingSpeed = 10; // How often to move the window (ms)

p {
  final new JWindow window;
  window.setSize(windowSize, windowSize);
  window.setVisible(true);
  window.setAlwaysOnTop(true);
  JPanel panel = singleColorPanel(Color.red);
  window.setContentPane(panel);
  revalidate(window);
  final new Robot robot;
  panel.addMouseListener(new MouseAdapter {
    // public void mousePressed(final MouseEvent e) {}

    public void mouseReleased(final MouseEvent e) {
      print("release! " + e);
      window.setVisible(false);
      int b = e.getButton();
      final int mod =
        b == 1 ? InputEvent.BUTTON1_DOWN_MASK
        : b == 2 ? InputEvent.BUTTON2_DOWN_MASK
        : InputEvent.BUTTON3_DOWN_MASK;
      swingLater(clickDelay, r {
        print("clicking " + mod);
        robot.mousePress(mod);
        robot.mouseRelease(mod);
      });
    }
  });

  swingEvery(window, trackingSpeed, r {
    Point p = getMouseLocation();
    window.setLocation(p.x-windowSize/2, p.y-windowSize/2);
    //print("moving");
  });
}

这篇关于java - 检测鼠标单击屏幕上的任意位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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