Java: Holding the cursor in an area

2019-07-04 04:35发布

问题:

For those of you who have played Madness Interactive, one of the most frustrating things is when the cursor leaves the game area, and you accidentally click. This causes the game to defocus and your character dies in a matter of seconds. To fix this, I'd like to make a java application that I can run in the background that will hold the cursor inside the screen until I press a key, like ESC or something.

I see two ways of implementing this, but I don't know if either of them are workable.

  1. Make an AWT frame that matches the size of Madness Interactive's render area, and control the cursor using that.
  2. Use some out-of-context operating system calls to keep the cursor in a given area.

Advantage of approach #1: Much easier to implement resizing of the frame so that user can see the shape and position of the enclosed area.

Potential Problems with approach #1: The AWT Frame would likely need to steal focus from the browser window the game is running in, making the whole solution pointless.

My question is, are either of these approaches viable? If not, is there a viable option?

EDIT: I am willing to use another programming language if necessary.

EDIT2: I might develop a browser plugin for this, but I've never done that kind of development before. I'll research it.

回答1:

If this is for a browser-based game, consider writing a greasemonkey script, which acts as a browser extension that can be filtered to only run on the game's site.

In the simplest case, assume the clickable regions are (0,0) - (300,400), then you can add the following event handler to the page:

$(document).on('click', function(event) {
  if (event.pageX > 300 || event.pageY > 400) {
    return false;
  }
});

You can further refine your script to do the following:

  1. resize the browser to be the perfect size for playing the game
  2. instead of checking the absolute x,y coords of the click, check if it is inside an element of the page that you don't want to receive the click
  3. add custom key bindings to umm.. help you at the game
  4. write a javascript bot that can play the game itself


回答2:

If you're still interested in working in Java, here's a possible solution for you.

First, in order to limit the cursor within an area, you could use the Java Robot class.

mouseMove(int x, int y);

Then, you could use AWT's MouseInfo to get the position of the mouse cursor.

PointerInfo mouseInfo = MouseInfo.getPointerInfo();
Point point = mouseInfo.getLocation();
int x = (int) point.getX();
int y = (int) point.getY();

Then, whenever the x and y value of the mouse cursor go beyond a certain point, move them back using the Java Robot class.



标签: java cursor awt