Adam Hasan
Adam Hasan

Reputation: 57

Executing a function when key combination is pressed

I'm adding some functionality to a menubar app. I want to execute a few lines of code that copies some text to the clipboard when a combination of keys are pressed (e.g. cmd + alt + L). This should work globally, i.e any time these keys are pressed.

Not sure how to go about doing this, I tried overriding the keyDown method but it gives an error in AppDelegate.swift saying that there's no method to override.

Upvotes: 2

Views: 839

Answers (1)

Rajmund Zawiślak
Rajmund Zawiślak

Reputation: 942

First step you need to add a global monitor.

NSEvent.addGlobalMonitorForEvents(matching: .keyDown, handler: {
    self.keyDown(with: $0)
})

But it can be also your func.

Second step is to handle these three keys

Read flags from NSApp.currentEvent?.modifierFlags and check if they contain .option and .command flags

Example

guard let flags = NSApp.currentEvent?.modifierFlags else {
   return
}
let optionKeyIsPressed = flags.contains(.option)

At last key you can read from NSEvent property keyCode.

The keyCode of later "L" you can read from kVK_ANSI_L

Hope it's all that you need to solve your problem, good luck.

Upvotes: 2

Related Questions