我的 OSX 应用程序的目标是用鼠标手势切换空间。我想在按下鼠标中键时通过向右或向左移动鼠标来切换空格。我已经捕捉到了我想要的鼠标手势,但我无法以编程方式切换空间。我试图模拟按 ctrl+右箭头或 ctrl+左箭头,但它不起作用。我的整个班级如下所示。
import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
var mouseLocation: NSPoint { NSEvent.mouseLocation }
var downX:CGFloat?
func applicationDidFinishLaunching(_ aNotification: Notification) {
NSEvent.addGlobalMonitorForEvents(matching: [.otherMouseDown]) { event in
self.downX = self.mouseLocation.x;
}
NSEvent.addGlobalMonitorForEvents(matching: [.otherMouseUp]) { event in
if(self.mouseLocation.x - self.downX! > 0) {
print("swipe right")
let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
let cmdd = CGEvent(keyboardEventSource: src, virtualKey: 0x37, keyDown: true)
let cmdu = CGEvent(keyboardEventSource: src, virtualKey: 0x37, keyDown: false)
let spcd = CGEvent(keyboardEventSource: src, virtualKey: 0x7C, keyDown: true)
let spcu = CGEvent(keyboardEventSource: src, virtualKey: 0x7C, keyDown: false)
let loc = CGEventTapLocation.cghidEventTap
cmdd?.post(tap: loc)
spcd?.post(tap: loc)
spcu?.post(tap: loc)
cmdu?.post(tap: loc)
} else {
print("swipe left")
let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
let cmdd = CGEvent(keyboardEventSource: src, virtualKey: 0x37, keyDown: true)
let spcd = CGEvent(keyboardEventSource: src, virtualKey: 0x7B, keyDown: true)
let spcu = CGEvent(keyboardEventSource: src, virtualKey: 0x7B, keyDown: false)
let cmdu = CGEvent(keyboardEventSource: src, virtualKey: 0x37, keyDown: false)
spcd?.flags = CGEventFlags.maskCommand;
let loc = CGEventTapLocation.cghidEventTap
cmdd?.post(tap: loc)
spcd?.post(tap: loc)
spcu?.post(tap: loc)
cmdu?.post(tap: loc)
}
}
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}