Skip to content

Instantly share code, notes, and snippets.

@hellvesper
Created February 20, 2022 10:43
Show Gist options
  • Save hellvesper/c5c0e8227e4339a39ac8ea1c437d32fd to your computer and use it in GitHub Desktop.
Save hellvesper/c5c0e8227e4339a39ac8ea1c437d32fd to your computer and use it in GitHub Desktop.
keyboard kernel events
import Foundation
import Cocoa
//@NSApplicationMain
class ApplicationDelegate: NSObject, NSApplicationDelegate {
// @IBOutlet var window: NSWindow!
// @IBOutlet private var text: NSTextField!
private var timer: Timer?
private var eventStrings: [String] = []
private var counter: UInt64 = 0
private var timestamp = NSDate().timeIntervalSince1970
func applicationDidFinishLaunching(_: Notification) {
// window.level = NSWindow.Level.floating
let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true]
if !AXIsProcessTrustedWithOptions(options) {
print("Untrusted process!")
return
}
NSEvent.addGlobalMonitorForEvents(
matching: [NSEvent.EventTypeMask.keyDown, NSEvent.EventTypeMask.keyUp, NSEvent.EventTypeMask.flagsChanged],
handler: { (event: NSEvent) in
switch event.type {
case .keyDown:
self.updateEventStrings(String(format: "keyDown %d", event.keyCode))
case .keyUp:
self.updateEventStrings(String(format: "keyUp %d", event.keyCode))
case .flagsChanged:
self.updateEventStrings(String(format: "flagsChanged %d", event.keyCode))
default:
break
}
}
)
}
func applicationWillTerminate(_: Notification) {}
func applicationShouldTerminateAfterLastWindowClosed(_: NSApplication) -> Bool {
return true
}
private func updateEventStrings(_ string: String) {
print(string)
print(NSDate().timeIntervalSince1970 - timestamp)
timestamp = NSDate().timeIntervalSince1970
}
}
let application = NSApplication.shared
let applicationDelegate = ApplicationDelegate()
application.delegate = applicationDelegate
application.activate(ignoringOtherApps: true)
application.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment