Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSX Swift : How to listen to Keypress?

Tags:

macos

swift

I'm currently developing an application in OSX and I want to open my application when the user press a keyboard combos.

like image 296
jezrielbajan Avatar asked Jul 18 '17 03:07

jezrielbajan


1 Answers

Yes It Is Possible

If your applications was already opened by the user, you need only implement the keyDown(with event: NSEvent) function:

func keyDown(with event: NSEvent) {
    guard let e = event.characters else {
        return
    }
    //Do something based on keyboard input
}

If you are trying to get access to keys when your application isn't open, you've essentially implemented a keylogger

But You Really Shouldn't

From your question, it would seem that you want the latter option. This is problematic for 3 reasons:

  1. It is ridiculously insecure. You are storing extremely sensitive data outside of your application's sandbox, easily visible to prying eyes.
  2. It is a serious breach of trust. No other third party applications perform this kind of behavior, and so, when your app does it, the user will definitely think twice about having it installed, primarily because:
  3. It is redundant. There are already ways in which users can automate the opening of various applications. Whether through
    • Their own Automator Script
    • A dedicated Launcher Application
    • By using a Finder Service

If, however, you're absolutely certain that you need this functionality, there is a generally agreed upon solution (edited)

Some Friendly Advice

As I'm sure you've noticed, your question wasn't particularly well received. To improve the responses you get in the future, just read the Stack Overflow Question Guide which, tl;dr entails:

  • Being specific about your question (what you've tried, context, etc.)
  • Googling your question beforehand
like image 120
Brandon Bradley Avatar answered Nov 02 '22 05:11

Brandon Bradley