用于鼠标单击的Swift命令行工具不会在Finder中多次单击

时间:2019-06-03 16:13:36

标签: swift cocoa click mouse

我在命令行工具应用中使用下面的代码来执行鼠标单击。我使用Shell脚本执行代码,并使用听写命令来触发它。这段代码几乎可以在除Finder之外的所有程序中使用,我不知道为什么。单击一次鼠标可以正常工作,但不能两次或三次。我不知道可能是什么问题。

// Get location
var ml = NSEvent.mouseLocation
ml.y = NSHeight(NSScreen.screens[0].frame) - ml.y
let location = CGPoint(x: ml.x, y: ml.y)


// Clicks
let e = CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: location, mouseButton: .left)!
e.setIntegerValueField(.mouseEventClickState, value: 2) // double click
e.post(tap: .cghidEventTap)

CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: location, mouseButton: .left)!.post(tap: .cghidEventTap)

1 个答案:

答案 0 :(得分:1)

你在这里

/// Clicks left mouse button twice
static func doubleClick() {

    var e = CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: Mouse.location, mouseButton: .left)!
    e.post(tap: .cghidEventTap)
    e = CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: Mouse.location, mouseButton: .left)!
    e.post(tap: .cghidEventTap)

    e = CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: Mouse.location, mouseButton: .left)!
    e.setIntegerValueField(.mouseEventClickState, value: 2)
    e.post(tap: .cghidEventTap)

    e = CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: Mouse.location, mouseButton: .left)!
    e.setIntegerValueField(.mouseEventClickState, value: 2)
    e.post(tap: .cghidEventTap)
}