在OS X中模拟单击和拖动 [英] Simulate Click and Drag in OS X

查看:103
本文介绍了在OS X中模拟单击和拖动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过编程来模拟鼠标动作.

I am trying to simulate mouse action via programming.

我无法可靠地点击并拖动动作.

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

For click and drag I am doing the following actions in the order mentioned below

  1. 在当前鼠标指针位置(仅一次)发布鼠标左键按下事件
  2. 移动鼠标(由于已经发送了鼠标按下事件,因此必须将其作为鼠标按下并拖动,并从初始鼠标位置中选择文本)
  3. 发布鼠标左键释放事件以结束鼠标保持动作.

在苹果应用程序(例如Xcode或Safari)中,此方法无法可靠运行(拖动时会突出显示文本,但是使用实际的鼠标,我可以通过单击和拖动来突出显示文本).也不能拖动图标.

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.

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

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.

推荐答案

我发现我们需要首先发送鼠标事件kCGEventLeftMouseDragged,以开始拖动和选择.

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

这篇关于在OS X中模拟单击和拖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆