Created
November 11, 2021 13:52
-
-
Save zhaorui/f2b860b4553f5a2cdc993a2c0a6d5109 to your computer and use it in GitHub Desktop.
A console app print all key events written by swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
import Foundation | |
@discardableResult | |
func acquirePrivileges() -> Bool { | |
let accessEnabled = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary) | |
if accessEnabled != true { | |
print("You need to enable the keylogger in the System Prefrences") | |
} | |
return accessEnabled | |
} | |
class AppDelegate: NSObject, NSApplicationDelegate { | |
private var monitor: Any? | |
func applicationDidFinishLaunching(_ notification: Notification) { | |
acquirePrivileges() | |
monitor = NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { event in | |
print(event) | |
} | |
} | |
} | |
print(Bundle.main) | |
// Turn off echo of TTY | |
var old = termios() | |
var new = termios() | |
tcgetattr(STDIN_FILENO, &old) | |
new = old | |
new.c_lflag &= ~(UInt(ICANON)) | |
new.c_lflag &= ~(UInt(ECHO)) | |
tcsetattr(STDIN_FILENO, TCSANOW, &new) | |
let appDelegate = AppDelegate() | |
NSApplication.shared.delegate = appDelegate | |
NSApp.activate(ignoringOtherApps: true) | |
NSApp.run() | |
// restore tty | |
tcsetattr(STDIN_FILENO, TCSANOW, &old) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment