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.)