Search code examples
swiftappkitnsevent

Monitor when app opens file


I am wondering if there is a way to monitor when a user presses open file (cmd+o) in any application.

I was thinking I could use addGlobalMonitorForEvents, but I was not sure how to get the specific on "Open File..." event.


Solution

  • I was able to mostly solve the problem by using this answer:

        let keycode = UInt16(0x1F)
        let keymask: NSEvent.ModifierFlags = NSEvent.ModifierFlags.command
        //...
        let options = NSDictionary(object: kCFBooleanTrue, forKey: kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString) as CFDictionary
        let trusted = AXIsProcessTrustedWithOptions(options)
        if (trusted) {
            NSEvent.addGlobalMonitorForEvents(matching: .keyUp, handler: self.handler)
        }