Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 can detect mouse clicks and get the mouse's position at any time, how can I do this with java?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
472 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

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.

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.

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");
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...