【问题标题】:How can I set the mouse position?如何设置鼠标位置?
【发布时间】:2012-04-21 03:42:26
【问题描述】:

我需要设置鼠标在屏幕上的位置。在其他一些类似的问题中,建议使用CGDisplayMoveCursorToPoint(CGDirectDisplayID display, CGPoint point),但我不知道如何获得CGDirectDisplayID。请告诉我如何获取CGDirectDisplayID 或其他设置鼠标位置的方法。

【问题讨论】:

    标签: macos core-graphics macos-carbon


    【解决方案1】:

    这个问题的真正答案是:

    CGMainDisplayID()
    

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

    CGDisplayMoveCursorToPoint(CGMainDisplayID(), point);
    

    【讨论】:

    • 这对我有用。在将它们转换为新语法后,我还尝试了一些快速解决方案,但它们似乎不再起作用。
    • CGMainDisplayID()kCGDirectMainDisplay有什么区别?
    • 这是最好的解决方案,即使对于 Swift 开发人员也是如此。谢谢!
    • 只有当您摆脱第二台显示器的世界时,这肯定是“真正的答案”?
    【解决方案2】:

    试试CGWarpMouseCursorPosition()。它不需要显示 ID。

    如果您想要一个显示 ID,您可以使用任何您喜欢的标准从[NSScreen screens] 返回的数组中选择一个元素。在该 NSScreen 对象上调用 -deviceDescription。从返回的字典中,使用键 @"NSScreenNumber" 调用 -objectForKey:

    【讨论】:

      【解决方案3】:

      这是一种方法:

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

      这会将光标移动到屏幕上的点 (10,10)(左上角,Apple 菜单旁边)。

      【讨论】:

      • 不起作用。出于某种原因,它正确设置了鼠标的 x,但是如果我尝试更改 Y,它会在屏幕的顶部和底部之间闪烁。即使我使用鼠标的当前位置。
      • 我刚刚尝试了各种xy 值,然后它移到了它们中的每一个。在发布之前,您是否以其他方式发布任何其他事件或修改此事件?
      【解决方案4】:

      这是一个 Swift 版本,仅供参考:

      let pt = CGPoint(x: 100, y: 10)
      let moveEvent = CGEventCreateMouseEvent(nil, .MouseMoved, pt, .Left)
      CGEventPost(.CGSessionEventTap, moveEvent);
      

      【讨论】:

        【解决方案5】:

        对我有帮助的答案的 Swift 3 版本:

        let pt = CGPoint(x: 100, y: 10)
        
        let moveEvent = CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, 
        mouseCursorPosition: pt, mouseButton: .left)
        
        moveEvent?.post(tap: .cgSessionEventTap)
        

        【讨论】:

        • 像魅力一样工作
        【解决方案6】:

        这是在 Swift 5 中:

        let pt = CGPoint(x: 100, y: 10)
                let moveEvent = CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: pt, mouseButton: .left)
                moveEvent?.post(tap: .cgSessionEventTap);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多