gpt4 book ai didi

swift - 应用程序在设置为后台时停止工作

转载 作者:行者123 更新时间:2023-11-28 06:06:37 27 4
gpt4 key购买 nike

当窗口在前台打开并且按下空格键时,代码工作正常,鼠标按预期移动,但是一旦我移动到另一个应用程序并按下空格键,鼠标就不再移动正如击键所预期的那样,即使应用程序设置为后台,我如何保持应用程序工作

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)
}
}
}
}

最佳答案

您需要捕获系统范围的事件。下面是一些示例代码,可以获取系统中的所有内容。请注意,您必须为 XCode(在开发期间)或您的应用程序(在 XCode 外部运行)启用辅助模式才能正常工作。

func applicationDidFinishLaunching(_ aNotification: Notification) {
if getAccessibility() {
snarfKeys()
}
// etc...
}

func getAccessibility() -> Bool {
let trusted = AXIsProcessTrusted()
if !trusted {
print("process is not trusted")
}
return trusted
}

func snarfKeys() {
NSEvent.addGlobalMonitorForEvents(matching: .keyUp, handler: keyPress)
NSEvent.addGlobalMonitorForEvents(matching: .leftMouseUp, handler: mousePress)
}

snarfKeys 有神奇的作用,但如上文和代码中所述,该进程需要受信任才能添加全局事件监控。

关于swift - 应用程序在设置为后台时停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030907/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com