这是我用来模拟左键单击的代码,但每次执行时,都会出现与右键单击相关的菜单。 我该如何解决这个问题?
func clickLeft() {
var mouseLoc = NSEvent.mouseLocation()
mouseLoc.y = NSHeight(NSScreen.screens()![0].frame) - mouseLoc.y
let point = CGPoint(x: mouseLoc.x, y: mouseLoc.y)
let mouseDown = CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left)
let mouseUp = CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left)
mouseDown?.post(tap: .cghidEventTap)
usleep(500)
mouseUp?.post(tap: .cghidEventTap)
}
答案 0 :(得分:0)
愚蠢的我,我把这个功能链接到一个关键事件,其中包括按住控制键。很明显,上下文菜单必须出现。
答案 1 :(得分:0)
上面的答案对我根本不起作用。
但是,我所需的正是@schnesim所做的-通过模拟单击来打开上下文菜单。
要单击编程鼠标,请按照以下步骤操作: (XCode9.4.1。Swift4.1.2)。
1)禁用应用沙箱How to simulate mouse click from Mac App to other Application
2)我修改了问题代码:
import Cocoa
class ViewController: NSViewController {
@IBOutlet var testMenu: NSMenu!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func rightMouseButtonSimulationButtonClicked(_ sender: NSButton) {
self.simulateMouseClick(.right)
}
func simulateMouseClick(_ mouseButtonClicked: CGMouseButton) {
var mouseLocation = NSEvent.mouseLocation
var mouseTypeUp: CGEventType!
var mouseTypeDown: CGEventType!
switch mouseButtonClicked {
case .left:
mouseTypeUp = .leftMouseUp
mouseTypeDown = .leftMouseDown
case .right:
mouseTypeUp = .rightMouseUp
mouseTypeDown = .rightMouseDown
case .center:
mouseTypeUp = .otherMouseUp
mouseTypeDown = .otherMouseDown
}
mouseLocation.y = NSHeight(NSScreen.screens[0].frame) - mouseLocation.y
let point = CGPoint(x: mouseLocation.x, y: mouseLocation.y)
let mouseDown = CGEvent(mouseEventSource: nil, mouseType: mouseTypeDown, mouseCursorPosition: point, mouseButton: CGMouseButton(rawValue: mouseButtonClicked.rawValue)!)
let mouseUp = CGEvent(mouseEventSource: nil, mouseType: mouseTypeUp, mouseCursorPosition: point, mouseButton: CGMouseButton(rawValue: mouseButtonClicked.rawValue)!)
mouseDown?.post(tap: .cghidEventTap)
usleep(500)
mouseUp?.post(tap: .cghidEventTap)
}
}