背景
做一个小demo,需要实现热键功能。
通过搜索和问AI折腾了一番,基本实现了功能,通过Combine提供的RegisterEventHotKey函数实现。
不过这个操作需要把程序添加到系统【隐私与安全】里的【辅助功能】列表里才能生效。
如下图
问题
Max上的微信和企业微信,都提供了热键功能,用来启动屏幕截图。发现它们都没有在【辅助功能】列表里,如上图所示。
所以想问问各位大神,有什么方式实现热键,不用开启辅助功能权限。
实现代码
swift
import SwiftUI
import Carbon
import Combine
class HotkeyViewModel: ObservableObject {
private var hotKeyRef: EventHotKeyRef?
@Published var isPermissionGranted: Bool = false
init() {
requestAccessibilityPermission()
}
private func requestAccessibilityPermission() {
var trusted = false
let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true]
if #available(OSX 10.9, *) {
trusted = AXIsProcessTrustedWithOptions(options)
} else {
trusted = AXIsProcessTrusted()
}
// 没有把程序添加到【辅助功能】列表里,trusted会为false, 注册热键会不成功
if !trusted {
print("Please enable accessibility permissions")
return
}
isPermissionGranted = true
}
func registerHotkey() {
var eventType = EventTypeSpec()
eventType.eventClass = OSType(kEventClassKeyboard)
eventType.eventKind = UInt32(kEventHotKeyPressed)
let eventHandler: EventHandlerUPP = { (nextHandler, theEvent, userData) -> OSStatus in
print("Hotkey pressed!")
return noErr
}
var hotKeyID = EventHotKeyID()
hotKeyID.signature = OSType(1)
hotKeyID.id = UInt32(kVK_ANSI_A)
let modifiers = UInt32(cmdKey | controlKey)
RegisterEventHotKey(UInt32(kVK_ANSI_A), modifiers, hotKeyID, GetApplicationEventTarget(), 0, &hotKeyRef)
InstallEventHandler(GetEventDispatcherTarget(), eventHandler, 1, &eventType, nil, nil)
}
}
struct ContentView: View {
@StateObject var viewModel = HotkeyViewModel()
var body: some View {
VStack {
Text("Accessibility Permission: \(viewModel.isPermissionGranted ? "Granted" : "Not Granted")")
.padding()
Button("Register Hotkey") {
viewModel.registerHotkey()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}