Reputation: 314
I am trying to simulate mouse action via programming.
I am not able to do click and drag action reliably.
For click and drag I am doing the following actions in the order mentioned below
In apple applications such as Xcode, or Safari, this method does not work reliably (It docent highlight text when dragged, but with actual mouse I can highlight text by click and drag). Cannot drag icons either.
However in Firefox, this technique works. The selection follows mouse! That is as we move mouse pointer, the selection also changes accordingly, which is what I need.
The following is the code I use to send mouse tap events.
-(void)_sendMouseEvent:(int)mouseEvent withMouseButton:(CGMouseButton)mouseBtn
{
CGEventRef ourEvent = CGEventCreate(NULL);
NSPoint mouseLoc = CGEventGetLocation(ourEvent); //get current mouse position
CGEventRef mouseClick = CGEventCreateMouseEvent(
NULL,
mouseEvent,
mouseLoc,
mouseBtn
);
CGEventPost(kCGHIDEventTap, mouseClick);
CFRelease(ourEvent);
CFRelease(mouseClick);
}
I did try sending mouse down events at regular intervals, but it made no change.
Do you have any ideas on what I am doing wrong? Please suggest any workarounds that come to your mind.
Upvotes: 2
Views: 2482
Reputation: 314
I found out that we need to send mouse event kCGEventLeftMouseDragged
first, to start dragging and selecting.
[self _sendMouseEvent:kCGEventLeftMouseDragged withMouseButton:kCGMouseButtonLeft]; //Start draging.
-(void)_sendMouseEvent:(int)mouseEvent withMouseButton:(CGMouseButton)mouseBtn
{
CGEventRef ourEvent = CGEventCreate(NULL);
NSPoint mouseLoc = CGEventGetLocation(ourEvent); //get current mouse position
CGEventRef mouseClick = CGEventCreateMouseEvent(
NULL,
mouseEvent,
mouseLoc,
mouseBtn
);
CGEventPost(kCGHIDEventTap, mouseClick);
CFRelease(ourEvent);
CFRelease(mouseClick);
}
Upvotes: 2