macOS 模拟触摸板向下滑动

今天需要在 macOS 上模拟触控板滑动事件,并且希望模拟自然的人类手势,即速度由慢到快。用 Swift 来实现,并控制滑动的时间间隔,目标是每隔 4 到 8 秒执行一次向下滑动的操作,滑动时速度逐步加快。简单记录一下:

import Foundation
import CoreGraphics

func simulateAcceleratingScrollDown() {
    let totalSteps = 25
    let initialScrollAmount: Int32 = -5
    let maxScrollAmount: Int32 = -25
    let initialDelay: TimeInterval = 0.1
    let minDelay: TimeInterval = 0.02
    
    for step in 1...totalSteps {
        let scrollAmount = initialScrollAmount + (Int32(step) * (maxScrollAmount - initialScrollAmount) / Int32(totalSteps))
        let currentDelay = initialDelay - (initialDelay - minDelay) * Double(step) / Double(totalSteps)
        let scrollEvent = CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 1, wheel1: scrollAmount, wheel2: 0, wheel3: 0)
        
        scrollEvent?.post(tap: .cghidEventTap)
        Thread.sleep(forTimeInterval: currentDelay)
    }
}

func randomInterval() -> TimeInterval {
    return TimeInterval(arc4random_uniform(5) + 4)
}

func startRandomScrolling() {
    let interval = randomInterval()
    Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { _ in
        simulateAcceleratingScrollDown()
        startRandomScrolling()
    }
}

RunLoop.current.run()

解释:

  • simulateAcceleratingScrollDown(): 模拟触控板的滑动动作,滚动步数由慢到快,每步滚动的像素量逐渐增加,延时逐渐缩短。
  • randomInterval(): 生成 4 到 8 秒的随机时间间隔。
  • startRandomScrolling(): 定时器每次等待随机时间后调用滑动事件,并继续递归调用。

解决 macOS 上的 mds_store 高 CPU 占用并停用 Spotlight 索引 腾讯云主机移除监控程序