How to Simulate Mouse Click from MAC App to Other Application

How to programmatically simulate a mouse click without moving mouse in Cocoa

I know this is an old thread, but I wanted to post an answer just in case anybody stumbles upon this.

The two best ways to do this are actually completely platform independent. (Unless you feel like using C, which is unnecessarily verbose for this in my opinion, but if you want to use it see this answer)

1) The easiest way is to use javAuto. (Note: javAuto has moved here). It's pretty much a java program the can compile and run basic automation scripts cross platform. For simulating a mouse click you can use this command:

mouseClick(button, x, y);

For simulating a mouseClick without moving the mouse you can use this:

// get cursor coordinates
int cPos[] = cursorGetPos();

// mouse click at the coordinates you want
mouseClick("left", x, y);

// instantly move the mouse back
mouseMove(cPos[0], cPos[1]);

Since the mouseClick and mouseMove commands don't involve any interim mouse movements, a click will happen at (x, y) but the mouse won't move at all.

2) The next best way to do this is to use regular Java, which will involve a bit more code than the same process in javAuto.

import java.awt.*;
import java.awt.event.InputEvent;

public class example {
public static void main(String[] args) {
//get the current coordinates
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int xOrig = (int)b.getX();
int yOrig = (int)b.getY();

try {
//simulate a click at 10, 50
Robot r = new Robot();
r.mouseMove(10, 50);
r.mousePress(InputEvent.BUTTON1_MASK); //press the left mouse button
r.mouseRelease(InputEvent.BUTTON1_MASK); //release the left mouse button

//move the mouse back to the original position
r.mouseMove(xOrig, yOrig);
} catch (Exception e) {

Simulating mouse clicks on Mac OS X does not work for some applications

What you need to do to convince these applications that you have in fact generated a click is to explicitly set the value of the "click state" field on the mouse up event to 1 (it defaults to 0). The following code will do it:

CGEventSetIntegerValueField(event, kCGMouseEventClickState, 1);

It also has to be set to 1 for the mouse down, but by using CGEventCreateMouseEvent() rather than CGEventCreate() that gets done for you.

I have tested this and it works in the 'i' buttons in the dashboard and the Spotlight search results.

(As an aside, if you were simulating a double click you would need to set the click state to 2 for both the mouse down and mouse up events of the second click.)

Related Topics

Leave a reply