How can I set the mouse position?

前端 未结 5 1403
谎友^
谎友^ 2021-01-15 03:54

I need to set the position of the mouse on the screen. In some other similar question, it was suggested to use CGDisplayMoveCursorToPoint(CGDirectDisplayID display, CG

相关标签:
5条回答
  • 2021-01-15 04:04

    Here's a way to do it:

    // coordinate at (10,10) on the screen
    CGPoint pt;
    pt.x = 10;
    pt.y = 10;
    
    CGEventRef moveEvent = CGEventCreateMouseEvent(
        NULL,               // NULL to create a new event
        kCGEventMouseMoved, // what type of event (move)
        pt,                 // screen coordinate for the event
        kCGMouseButtonLeft  // irrelevant for a move event
    );
    
    // post the event and cleanup
    CGEventPost(kCGSessionEventTap, moveEvent);
    CFRelease(moveEvent);
    

    This will move the cursor to point (10,10) on screen (the upper left, next to the Apple menu).

    0 讨论(0)
  • 2021-01-15 04:07

    Here's a Swift version, just for kicks:

    let pt = CGPoint(x: 100, y: 10)
    let moveEvent = CGEventCreateMouseEvent(nil, .MouseMoved, pt, .Left)
    CGEventPost(.CGSessionEventTap, moveEvent);
    
    0 讨论(0)
  • 2021-01-15 04:13

    The real answer to this question is:

    CGMainDisplayID()
    

    https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/Quartz_Services_Ref/index.html#//apple_ref/c/func/CGMainDisplayID

    CGDisplayMoveCursorToPoint(CGMainDisplayID(), point);
    
    0 讨论(0)
  • 2021-01-15 04:21

    Try CGWarpMouseCursorPosition(). It doesn't require a display ID.

    If you want a display ID, you can pick an element, using whatever criteria you like, from the array returned by [NSScreen screens]. Invoke -deviceDescription on that NSScreen object. From the dictionary that's returned, invoke -objectForKey: with the key @"NSScreenNumber".

    0 讨论(0)
  • 2021-01-15 04:25

    Swift 3 version of the answer that helped me:

    let pt = CGPoint(x: 100, y: 10)
    
    let moveEvent = CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, 
    mouseCursorPosition: pt, mouseButton: .left)
    
    moveEvent?.post(tap: .cgSessionEventTap)
    
    0 讨论(0)
提交回复
热议问题