Simulate left click on cursor position in Swift Xcode

Viewed 119

I'm Trying to Simulate a left click in Swift Xcode. I've found this code online but it moves the cursour, Is there a way to keep the cursor in it's current spot and click?

import Foundation

let source = CGEventSource.init(stateID: .hidSystemState)
let position = CGPoint(x: 75, y: 100)
let eventDown = CGEvent(mouseEventSource: source, mouseType: .leftMouseDown, mouseCursorPosition: position , mouseButton: .left)
let eventUp = CGEvent(mouseEventSource: source, mouseType: .leftMouseUp, mouseCursorPosition: position , mouseButton: .left)


eventDown?.post(tap: .cghidEventTap)

//eventDown?.postToPid(71028)
usleep(500_000)
//eventUp?.postToPid(71028)
eventUp?.post(tap: .cghidEventTap)
2 Answers

I think the problem in your current code is the following line :

let position = CGPoint(x: 75, y: 100)

You clearly assign a new position to your mouse cursor. You should use the mouseLocationOutsideOfEventStream, like this :

let position = self.window.mouseLocationOutsideOfEventStream as CGPoint

Be aware that this returns a NSPoint that you may have to cast as a CGPoint (like I did).

As you are working with a Playground, here is a much detailed sample :

import Cocoa
import PlaygroundSupport

// You need to create a view to provide to your current PlaygroundPage
let currentView = NSView()
PlaygroundPage.current.liveView = currentView

// Here you are able to get your cursor current location
let cursorPosition = currentView.window!.mouseLocationOutsideOfEventStream as CGPoint

// Then you are able to run your code below using the cursorPosition variable
let source = CGEventSource.init(stateID: .hidSystemState)
let eventDown = CGEvent(mouseEventSource: source, mouseType: .leftMouseDown, mouseCursorPosition: cursorPosition , mouseButton: .left)
let eventUp = CGEvent(mouseEventSource: source, mouseType: .leftMouseUp, mouseCursorPosition: cursorPosition , mouseButton: .left)


eventDown?.post(tap: .cghidEventTap)

//eventDown?.postToPid(71028)
usleep(500_000)
//eventUp?.postToPid(71028)
eventUp?.post(tap: .cghidEventTap)

You should disable application sandboxing in order to make your code work

Related