Simulate Click and Drag in OS X

心已入冬 提交于 2020-01-14 04:45:59

问题


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

  1. Post left mouse button pressed event at current mouse pointer position (only once)
  2. 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)
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!