2011-11-21 47 views
0

我有一个小程序,它应该将鼠标移动到某个点(在本例中为100,100),当它从屏幕左侧经过500像素时。 CGEventTap正确接收kCGEventMouseMoved事件,但CGEventSetLocation似乎只移动事件,如mouseUp,而不是MouseMoved。您可以使用CGEventSetLocation移动鼠标吗?

是否可以使用CGEventSetLocation移动鼠标?如果不是,还有其他方法可以做到吗?

我包括我的代码在这里:

CGEventRef 
mouse_filter(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) { 
    if (type != kCGEventMouseMoved) 
     return event; 

    CGPoint point = CGEventGetLocation(event); 
    CGPoint target = CGPointMake(500,point.y); 
    if (point.x >= 500){ 
     CGEventSetLocation(event,target); 
     printf("(%f,%f)\n", point.x, point.y); 
    } 
    return event; 
} 

int 
main(int argc, char *argv[]) { 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    CFRunLoopSourceRef runLoopSource; 
    CGEventMask event_mask; 
    event_mask = (1 << kCGEventMouseMoved); 
    CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, event_mask, mouse_filter, NULL); 

    if (!eventTap) { 
     NSLog(@"Couldn't create event tap!"); 
     exit(1); 
    } 

    runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0); 

    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes); 

    CGEventTapEnable(eventTap, true); 

    CFRunLoopRun(); 

    CFRelease(eventTap); 
    CFRelease(runLoopSource); 
    [pool release]; 

    exit(0); 
} 

回答

0

令人困惑的是,the function you want其实并不在Quartz事件服务,但Quartz Display Services

+0

有趣的是,你应该指出,我实际上是在2.5小时前发现它的,并且我要回答我自己的问题,但决定给社区一个机会。我正在给你接受的答案。如果您碰巧知道我是否应该使用CGAssociateMouseAndMouseCursor(0),请告诉我。看起来这可能是有益的? – BumbleShrimp

+0

@JonathonG正如文档所说:“当你调用这个函数来断开光标和鼠标的连接时,应用程序收到的所有事件都有一个固定的绝对位置,但包含鼠标增量(X和Y的变化)数据。”所以你只会如果您希望鼠标像操纵杆一样操作,请将鼠标与鼠标断开连接。主要用于3D游戏和某些类型的控件(Final Cut有一个或两个使用它)。 –