CGEventLeftMouseDragged仅在最后更新UI

时间:2013-10-09 20:36:30

标签: cocoa

我正在尝试模拟移动鼠标,单击某个项目并拖动它。

有问题的项目是通过粘贴板拖动的(如果您是手动执行)。

代码工作正常,除了拖动项目的拖动图像仅出现在序列的末尾,鼠标拖动时不会显示,

我想知道它是否是一个runloop的东西,或者我缺少的东西,任何帮助赞赏!

//Underlying code of the draggable item (how it's dragged)
[self dragImage:_dragImage
             at:dragPosition
         offset:NSZeroSize
          event:theEvent
     pasteboard:pb
         source:self
      slideBack:YES];

和我用来模拟的代码是:

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

    for (int i = 0; i < 100; i++)
    {
        CGEventRef move1 = CGEventCreateMouseEvent(
                                                   NULL, kCGEventMouseMoved,
                                                   CGPointMake(100, 200+i),
                                                   kCGMouseButtonLeft
                                                   );
        CGEventPost(kCGHIDEventTap, move1);
        CFRelease(move1);
        [NSThread sleepForTimeInterval:0.01];
    }

    CGEventRef click1_down = CGEventCreateMouseEvent(
                                                     NULL, kCGEventLeftMouseDown,
                                                     CGPointMake(100, 290),
                                                     kCGMouseButtonLeft
                                                     );
    CGEventPost(kCGHIDEventTap, click1_down);
    CFRelease(click1_down);
    [NSThread sleepForTimeInterval:0.01];

    //int i = 0;
    for (int i = 0; i < 100; i++)
    {
        CGEventRef click1_drag = CGEventCreateMouseEvent(
                                                         NULL, kCGEventLeftMouseDragged,
                                                         CGPointMake(100+i, 290),
                                                         kCGMouseButtonLeft
                                                         );
        CGEventPost(kCGHIDEventTap, click1_drag);
        CFRelease(click1_drag);

        [NSThread sleepForTimeInterval:0.01];
    }
});

有用的链接:Simulating mouse input programmatically in OS X

1 个答案:

答案 0 :(得分:1)

是的,它是“一个runloop的东西” - 你正在“睡觉”主线程,所以阻止它以通常的方式处理Drag and Drop东西。

我认为您可以通过将现有广告单元更改为dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)..._PRIORITY_HIGH来解决此问题。