Objective-c – Clicking the mouse down to drag objects on Mac

cocoamacosobjective c

I've been using the following code to issue clicks programmatically on a Mac

void PostMouseEvent(CGMouseButton button, CGEventType type, const CGPoint point) 
{
    CGEventRef theEvent = CGEventCreateMouseEvent(NULL, type, point, button);
    CGEventSetType(theEvent, type);
    CGEventPost(kCGHIDEventTap, theEvent);
    CFRelease(theEvent);
}

void Click(const CGPoint point) 
{
    PostMouseEvent(kCGMouseButtonLeft, kCGEventMouseMoved, point);
    NSLog(@"Click!");
    PostMouseEvent(kCGMouseButtonLeft, kCGEventLeftMouseDown, point);
    PostMouseEvent(kCGMouseButtonLeft, kCGEventLeftMouseUp, point);
}

Now, I'm trying to click down to be able to drag objects, like a scroll bar or an application's window. I'm using the following:

PostMouseEvent(kCGMouseButtonLeft, kCGEventMouseMoved, point);
NSLog(@"Click Down!");
PostMouseEvent(kCGMouseButtonLeft, kCGEventLeftMouseDown, point);

When i ran the code above something interesting will happen, when the left mouse down is issue nothing seem to happen, I move my mouse and the window doesn't move, however when I added a mouse up event then the window jumped to the location where I supposedly dragged it. this is sort of OK, however, how do I can make the mouse click down and drag an object?

Note: I do have a whole method to see when the mouse stopped moving so I can click up.

please post code.
Thanks

Best Answer

The only way to do what you want is setting a active CGEventTap to get a editable stream of kCGEventMouseMoved events and change them into kCGEventLeftMouseDragged events in the callback of the CGEventTap (obviously you need to synthesize the mouse down event first)

You would think that this is done automatically by sending a click event with no release and moving the mouse but that is not the case.

Related Topic