Search code examples
c++macosmacos-carbon

Posting MouseEvents to applications in OSX


I am trying to send mouse events to a (I think SDL/OpenGL) game that doesn't support a gamepad. I know I could just use one of the many Gamepad to Keyboard/Mouse applications available, but I thought it would be fun to write my own. The following code works fine except when the game is running:

// point is a CGPoint that is set earlier on...
CGEventRef event = CGEventCreateMouseEvent(NULL,kCGEventMouseMoved , point,  0);
CGEventSetType(event, kCGEventMouseMoved);// apparently there is a apple bug that requires this...
CGEventPost(kCGHIDEventTap, event);
CFRelease(event);

With this, I can move the cursor on my desktop, and even in the games menu's, however the only time the game gets it while in the actual game is when I move my physical mouse. Sending keyboard events works fine in the game, so I don't know what the problem is


Solution

  • I found out what the problem was, I had to use:

    CGEventSetIntegerValueField(event, kCGMouseEventDeltaX, dX);
    CGEventSetIntegerValueField(event, kCGMouseEventDeltaY, dY);
    

    to set the relative coordinates of the mouse move. I think this is because the game was warping the mouse to the center of the game window, and my application wasn't getting the mouse move events from that.