当窗口在前台打开时,代码工作正常,当我按空格键时,鼠标按预期移动,但是当我移动到另一个应用程序并按空格键时,鼠标不再移动正如按键所预期的那样,即使应用程序设置为后台,我如何保持应用程序正常工作
import Cocoa
class ViewController: NSViewController {
var timer: Timer!
@objc func movethemouse() {
let mouseLocx = NSEvent.mouseLocation.x
let mouseLocy = NSEvent.mouseLocation.y
let screenH = NSScreen.main?.frame.height
let deltaX = CGFloat(Int(1))
let deltaY = CGFloat(Int(1))
let newLoc = CGPoint(x: mouseLocx + deltaX , y: screenH! - mouseLocy - deltaY )
CGDisplayMoveCursorToPoint(CGMainDisplayID(), newLoc)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear() {
view.window?.makeFirstResponder(self)
}
override var acceptsFirstResponder : Bool {
return true
}
var count3=0
var flag = false
override func keyDown(with event: NSEvent) {
if (event.keyCode == 49){
flag = true
if count3 == 0 {
timer = Timer.scheduledTimer(timeInterval: 0.001, target:self, selector: #selector(ViewController.movethemouse), userInfo: nil, repeats:true)
print(event)
}
count3 += 1
}
}
override func keyUp(with event: NSEvent) {
print(event)
if (event.keyCode == 49) {
if flag {
timer.invalidate()
count3 = 0
print(event)
}
}
}
}
答案 0 :(得分:1)
您需要捕获系统范围的事件。这里有一些示例代码可以获取系统中的所有内容。请注意,您必须为XCode(开发期间)或您的应用程序(在XCode外部运行)启用辅助模式才能使其正常工作。
<FlatList
horizontal
contentOffset = {{x: ITEM_WIDTH * this.props.startAtIndex, y: 0}}
...
/>
snarfKeys发挥了神奇作用,但如上所述和代码中,需要信任该流程才能添加全局事件监控。