2

I want my Mac application to open its main window, and quit on any mouse movement.

It works, except I need to click on the window first, then move the mouse, in order for my application to quit.

To build this simple application, I used Xcode and the "Cocoa Mac" built-in project with "Use Storyboards", then in my ViewController.swift, I have edited as follow:

override func viewDidLoad() {
    super.viewDidLoad()
    NSEvent.addGlobalMonitorForEvents(matching: .mouseMoved) { event in
        NSApplication.shared.terminate(self);
    }
}

I'm thinking it might be a problem of giving focus first? However, when the application launches it seems to me it has already the focus on its main window.

Any thoughts where am I doing it wrong?


My final wish is to make the application go fullscreen, and it works, adding the one line as below. The problem is, after entering fullscreenmode, the "MouseMoved event" isn't responding anymore, even when I click inside the window:

override func viewDidLoad() {
    super.viewDidLoad()

    view.enterFullScreenMode(NSScreen.main!, withOptions: nil)

    NSEvent.addGlobalMonitorForEvents(matching: .mouseMoved) { event in
        NSApplication.shared.terminate(self);
    }
}

UPDATE (December 17, 2018):

As an update to my ticket I finally chose to quit my application on keyDown event (instead of mouseMoved event), which I handled this way:

class ViewController: NSViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

        override func keyDown(with event: NSEvent) {
            NSApplication.shared.terminate(self);
        }

        ...

    }

    ...

}

(Moreover it's compatible with the fullscreen mode, which is nice.)

Yoric
  • 1,761
  • 2
  • 13
  • 15
  • Please read [addGlobalMonitorForEvents(matching:handler:)](https://developer.apple.com/documentation/appkit/nsevent/1535472-addglobalmonitorforevents). It says "Note that your handler will not be called for events that are sent to your own application.". – Willeke Dec 14 '18 at 08:40
  • so is your "Update" an answer / solution to your question (which you should put below) or is it additional detail and you still have a problem? – Michael Dautermann Dec 17 '18 at 06:40
  • @MichaelDautermann: My update is a workaround. The "real" solution would be to handle the "mouseMoved" event correctly from within the application. – Yoric Dec 17 '18 at 07:01

0 Answers0