I am trying to simulate a mouse click event in the new “IPhone Mirroring” feature that mac has to offer, I can do it via code that needs to take control of my mouse (moves my mouse and performs the click) but I am looking for a way to do it without having to give control of my computer. since I would like to automate some tasks on my IPhone.
So far, I tried every single answer from StackOverFlow, nothing seems to help, here is my code.
import SwiftUI
import CoreGraphics
import AppKit
struct ContentView: View {
func simulateMouseClick() {
// Find target window
guard let targetApp = NSWorkspace.shared.runningApplications
.first(where: { $0.localizedName?.contains("iPhone Mirroring") == true }),
let windowList = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]],
let targetWindow = windowList.first(where: { ($0[kCGWindowOwnerPID as String] as? pid_t) == targetApp.processIdentifier }),
let bounds = targetWindow[kCGWindowBounds as String] as? [String: Any],
let x = bounds["X"] as? CGFloat,
let y = bounds["Y"] as? CGFloat,
let width = bounds["Width"] as? CGFloat,
let height = bounds["Height"] as? CGFloat,
let windowNumber = targetWindow[kCGWindowNumber as String] as? Int else {
return
}
// Move mouse and create click point
let point = CGPoint(x: x + width/2, y: y + height/2)
CGDisplayMoveCursorToPoint(CGMainDisplayID(), point)
// Create click events
guard let mouseDown = NSEvent.mouseEvent(
with: .leftMouseDown,
location: point,
modifierFlags: [],
timestamp: ProcessInfo.processInfo.systemUptime,
windowNumber: windowNumber,
context: nil,
eventNumber: 0,
clickCount: 1,
pressure: 1.0
)?.cgEvent,
let mouseUp = NSEvent.mouseEvent(
with: .leftMouseUp,
location: point,
modifierFlags: [],
timestamp: ProcessInfo.processInfo.systemUptime,
windowNumber: windowNumber,
context: nil,
eventNumber: 0,
clickCount: 1,
pressure: 1.0
)?.cgEvent else {
return
}
// Try to click twice
mouseDown.post(tap: .cghidEventTap)
usleep(100_000)
mouseUp.post(tap: .cghidEventTap)
usleep(200_000)
mouseDown.post(tap: .cghidEventTap)
usleep(100_000)
mouseUp.post(tap: .cghidEventTap)
}
var body: some View {
Button("Click Target Window") { simulateMouseClick() }
}
}