首页 > 解决方案 > 以编程方式控制 macOS 鼠标 - Swift 4

问题描述

我正在使用 Swift,我正在尝试弄清楚如何用我的 iPhone 控制我的 macOS 鼠标。我认为第一步是通过 macOS 应用程序以编程方式移动 MacOS 鼠标。我不确定我错过了什么或做错了什么。

import Cocoa
import CoreGraphics

class ViewController: NSViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

typealias CGDirectDisplayID = UInt32

func CGMainDisplayID() -> CGDirectDisplayID{

    return CGMainDisplayID()

}

func CGDisplayMoveCursorToPoint(_ display: CGDirectDisplayID,
                                _ point: CGPoint){
}

self.CGDisplayMoveCursorToPoint(CGMainDisplayID(),(25,400))

}

我收到一个错误:“预期声明”self.CGDisplayMoveCursorToPoint(CGMainDisplayID(),(25,400))

标签: swiftmacosmousemove

解决方案


我稍微改写了你的课。这应该完成你想要的:

typealias CGDirectDisplayID = UInt32

class ViewController: NSViewController
    {

    override func viewDidLoad()
        {
        super.viewDidLoad()
        moveCursor(onDisplay: mainDisplayID(), toPoint: CGPoint(x: 25, y: 400))
        }

    public func mainDisplayID() -> CGDirectDisplayID
        {
        return CGMainDisplayID()
        }

    public func moveCursor(onDisplay display: CGDirectDisplayID, toPoint point: CGPoint)
        {
        CGDisplayMoveCursorToPoint(display, point)
        }

    }

当前代码中最重要的错误是您的CGDisplayMoveCursorToPoint函数在其定义中没有任何内容,因此不会发生任何事情。此外,你不想这样命名你的函数,因为它们是由 Core Graphics 框架实现的,编译器不会喜欢这样。Alexander 的评论似乎对您有所帮助。

在此自定义moveCursor函数中,您可以调用其中一个CGDisplayMoveCursorToPoint(display, point)CGWarpMouseCursorPosition(point)- 它们在功能上是等效的,但不需要显示 ID。从那里您需要moveCursor在您的控制器生命周期方法之一中调用此方法。Alexander 的建议值得一提,但是对于开始并测试一切是否正常,您只需将其放入其中viewDidLoad,该函数将在视图加载后立即启动。

希望这可以帮助!


推荐阅读