问题
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
- Post left mouse button pressed event at current mouse pointer position (only once)
- Move the mouse (as mouse down event is already sent, it must act as mouse down and drag, selecting text from the initial mouse postion)
- Post left mouse button release event to end mouse hold action.
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.
回答1:
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);
}
来源:https://stackoverflow.com/questions/33911835/simulate-click-and-drag-in-os-x