hotPocket
hotPocket

Reputation: 69

Post right-click event using CGPostMouseEvent

I am trying to write a script that will be able to right-click on OS X 10.11.5. I have been using the Foundation framework on Objective-C to accomplish this. So far, I have been able to successfully left-click.

The script below is able to left click using CGPostMouseEvent, the documentation for which can be found in CGRemoteOperation.h.

The comments mention that I need a boolean_t for the final parameter in CGPostMouseEvent. I am not sure what that means, however I have tried the following combinations of params to no avail:

(pt, 1, 1, 0, 1)
(pt, 1, 1, (0, 1))
(pt, 1, 1, 2)

What is the proper final parameter for CGPostMouseEvent to trigger a right-click?

#import <Foundation/Foundation.h> 
#import <ApplicationServices/ApplicationServices.h>


int main(int argc, char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSUserDefaults *args = [NSUserDefaults standardUserDefaults];
    // grabs command line arguments -x and -y
    //
    int x = [args integerForKey:@"x"];
    int y = [args integerForKey:@"y"];


    // The data structure CGPoint represents a point in a two-dimensional
    // coordinate system.  Here, X and Y distance from upper left, in pixels.
    //
    CGPoint pt;
    pt.x = x;
    pt.y = y;


    // This is where the magic happens.  See CGRemoteOperation.h for details.
    //
    // CGPostMouseEvent( CGPoint        mouseCursorPosition,
    //                   boolean_t      updateMouseCursorPosition,
    //                   CGButtonCount  buttonCount,
    //                   boolean_t      mouseButtonDown, ... )
    //
    // So, we feed coordinates to CGPostMouseEvent, put the mouse there,
    // then click and release.
    //

    CGPostMouseEvent(pt, 1, 1, 1);
    CGPostMouseEvent(pt, 1, 1, 0);


    [pool release];
    return 0;
}

Upvotes: 0

Views: 403

Answers (1)

bdash
bdash

Reputation: 18308

CGPostMouseEvent uses varargs to pass the state of buttons other than the left mouse button. The mouseButtonDown parameter indicates only whether or not the left mouse button is down. The state of other buttons should be passed after mouseButtonDown, in the varargs portion of the function signature. For the buttonCount argument you'll need to pass the total number of button states you're passing, including the left button.

The following sequence should post a mouse down event followed by a mouse up event for the right mouse button.

CGPostMouseEvent(pt, 1, 2, 0, 1);
CGPostMouseEvent(pt, 1, 2, 0, 0);

That said, CGPostMouseEvent has been deprecated for some time. Its replacement, CGEventCreateMouseEvent combined with CGEventPost, is easier to use.

Upvotes: 1

Related Questions