在 OS X 中模拟点击和拖动

Simulate Click and Drag in OS X

我正在尝试通过编程模拟鼠标操作。

我无法可靠地执行单击和拖动操作

对于点击和拖动,我按照下面提到的顺序执行以下操作

  1. Post 在当前鼠标指针位置按下鼠标左键事件(仅一次)
  2. 移动鼠标(因为已经发送了鼠标按下事件,它必须充当鼠标按下并拖动,从初始鼠标位置选择文本)
  3. Post 鼠标左键释放事件结束鼠标按住操作。

在 Xcode 或 Safari 等苹果应用程序中,此方法无法可靠地工作(它会在拖动时突出显示文本,但使用实际鼠标我可以通过单击和拖动来突出显示文本)。也不能拖动图标。

但是在 Firefox 中,此技术有效。选择跟随鼠标!那就是当我们移动鼠标指针时,选择也会相应地改变,这就是我所需要的。

以下是我用来发送鼠标点击事件的代码。

-(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);
}

我确实尝试定期发送鼠标按下事件,但没有任何改变。

你对我做错了什么有什么想法吗?请提出您想到的任何解决方法。

我发现我们需要先发送鼠标事件kCGEventLeftMouseDragged,才能开始拖动和选择。

[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);
}