How to Capture / Post system-wide Keyboard / Mouse events under Mac OS X?

前端 未结 3 1563
北恋
北恋 2020-12-23 15:45

For a scripting utility I need to be able to record a series of keyboard and mouse events that occur when an application has focus. The second part is being able to later se

3条回答
  •  温柔的废话
    2020-12-23 16:04

    For the latter part, posting events, use the CGEvent methods provided in ApplicationServices/ApplicationServices.h

    Here's an example function to move the mouse to a specified absolute location:

    #include 
    
    int to(int x, int y)
    {
        CGPoint newloc;
        CGEventRef eventRef;
        newloc.x = x;
        newloc.y = y;
    
        eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newloc,
                                            kCGMouseButtonCenter);
        //Apparently, a bug in xcode requires this next line
        CGEventSetType(eventRef, kCGEventMouseMoved);
        CGEventPost(kCGSessionEventTap, eventRef);
        CFRelease(eventRef);
    
        return 0;
    }
    

提交回复
热议问题