Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

swift - How to simulate mouse click from Mac App to other Application

I am trying to simulate mouse click on iphone simulator from macos App for that I am using CGEvents .

the process id is 33554 for iPhone simulator

let point = CGPoint(x: 500  , y:300)
let eventMouseDown = CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left)
let eventMouseUp = CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left)
eventMouseDown?.postToPid(33554)
eventMouseUp?.postToPid(33554)

I have also noticed that It simulates mouse click when ios simulator window is focused and only works for this toolbar but not for the simulator for example if I change CGPoint to (0,30) it will click on Simulator option

enter image description here

but when I am giving CGPoints to click app inside iOS Simulator its not working enter image description here

However, I am able to post Keyboard Event to Simulator using

let keyboardDown = CGEvent(keyboardEventSource: nil, virtualKey: 6, keyDown: true)
let keyboardUp = CGEvent(keyboardEventSource: nil, virtualKey: 6, keyDown: false)
keyboardDown?.postToPid(33554)
keyboardUp?.postToPid(33554)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of if you look at postToPid there is no documentation at all

PostToPID

So not even sure if it is suppose to work and if yes then when and when not. But you can post the event directly to screen using below code

//
//  main.swift
//  mouseplay
//
//  Created by Tarun Lalwani on 22/05/18.
//  Copyright ? 2018 Tarun Lalwani. All rights reserved.
//

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)

print("Hello, World!")

You can see it working also

Run demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...