全局快捷键(基于HotKey)

为了启动截屏功能,需要监听全局的快捷键。在AppDelegate中使用HotKey对全局快捷键cmd+shift+a进行注册:

import Cocoa
import HotKey

@main
class AppDelegate: NSObject, NSApplicationDelegate {
    
    let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.squareLength)
    let hotKey = HotKey(key: .a, modifiers: [.shift, .command])

    func applicationDidFinishLaunching(_ aNotification: Notification) {
               
        self.hotKey.keyUpHandler = {
            print("hello")
        }
        
        guard let button = self.statusItem.button else { return }
        button.image = NSImage(named: NSImage.Name("StatusBarIcon"))
        button.action = #selector(showMenu)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
    
    @objc func showMenu() {}
}

局部快捷键

局部快捷键用于监听应用内的一些键盘事件,比如回车完成Clip操作,Esc退出Clip操作:

import Cocoa
import HotKey

@main
class AppDelegate: NSObject, NSApplicationDelegate {
    
		// ... variables

    func applicationDidFinishLaunching(_ aNotification: Notification) {

				// local hotkey
        NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: {
		        (event) -> NSEvent? in
		        if ClipManager.shared.status != .off && event.keyCode == kVK_Escape {
								// 退出Clip之后的操作
		            ClipManager.shared.end()
		        }
		        if ClipManager.shared.status == .select && event.keyCode == kVK_Return {
								// 完成Clip之后的操作,post一个名为clipEnd的通知
		            NotificationCenter.default.post(name: NotiNames.clipEnd.name, object: self, userInfo: nil)
        }
		        return nil
        })

        // ... global hotkey and status bar item
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
    
}

截屏管理器 ➡️