How to handle escape key press event? [duplicate] - swift

This question already has answers here:
Swift - Capture keydown from NSViewController
(5 answers)
the "funk" sound when hitting escape key in app
(1 answer)
Closed 5 years ago.
In Swift, is there a function in Cocoa framework to handle the press so that you can register which keyboard key has been hit?
I'd like to get the escape key
UPDATED:
i just found that the noise was casued by
super.keyDown(with: event)
wich is not needed for the thing to work
why did u add that line?

Create a subclass of NSWindow and implement keyDown event:
import Cocoa
import Carbon.HIToolbox
class CustomWindow: NSWindow {
override func keyDown(with event: NSEvent) {
switch Int(event.keyCode) {
case kVK_Escape:
print("Esc pressed")
default:
break
}
super.keyDown(with: event)
}
}
This line:
import Carbon.HIToolbox
Lets you use handy constants for keys, such as kVK_Escape.
Set this class as your main window class in the Interface Builder and you're all set:
P.S. To do the same form NSViewController, in viewDidLoad do:
NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
self.keyDown(with: $0)
return $0
}
P.P.S. To mute "bang" sound, don't call super upon Escape key press - move super call to default:
default:
super.keyDown(with: event)
EDIT:
If you don't want any sound on Escape key press, then the following approach should be used:
Make an NSView subclass and set it to main view of the view controller:
import Cocoa
import Carbon.HIToolbox
class CustomView: NSView {
override func performKeyEquivalent(with event: NSEvent) -> Bool {
switch Int(event.keyCode) {
case kVK_Escape:
print("Esc pressed")
return true
default:
return super.performKeyEquivalent(with: event)
}
}
}

Related

How can I respond to a keyUp event?

I am writing a simple menu bar application for MacOS using SwiftUI. I would like the application to respond to the escape key. Using what I have pieced together so far, I have something like this:
extension NSWindow {
open override func keyDown(with event: NSEvent) {
print("keyDown: \(event.keyCode)")
}
open override func keyUp(with event: NSEvent) {
print("keyUp: \(event.keyCode)")
}
}
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// etc
}
}
The AppDelegate creates and launches a NSPopover.
When I run the application, I do get the keyUp messages, but, not the keyDown for some reason.
The question is how can I respond to the key from within the AppDelegate? Ultimately, I want to close the popover using the escape key, but I would also like to explore other possibilities.

Best strategy in swift to detect keyboad input in NSViewController

I want to detect keyboard input in my NSViewController.
The idea is to have several actions performed if the user presses certain keys followed by ENTER/RETURN.
I have checked if keyDown would be a appropriate way. But I would receive an event any time the user has pressed a key.
I also have though on using an NSTextField, set it to hidden and let it have the focus.
But maybe there are other better solution.
Any ideas?
Thanks
I've finally got a solution that I like.
First it has nothing todo with any hidden UI Elements but rather let the viewcontroller detect keyboard input.
var monitor: Any?
var text = ""
override func viewDidLoad() {
super.viewDidLoad()
self.monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: myKeyDownEvent)
}
override func viewWillDisappear() {
//Clean up in case your ViewController can be closed an reopened
if let monitor = self.monitor {
NSEvent.removeMonitor(monitor)
}
}
// Detect each keyboard event
func myKeyDownEvent(event: NSEvent) -> NSEvent {
// keyCode 36 is for detect RETURN/ENTER
if event.keyCode == 36 {
print(text)
text = ""
} else {
text.append( event.characters! )
}
return event
}

Click event NSTextField OSX [duplicate]

This question already has answers here:
Click inside swift 2.2 OSX [closed]
(2 answers)
Closed 6 years ago.
I am having multiple textfields and I won't to invoke an action method if the user clicks on a textfield, this is what I currently have:
override func mouseDown(theEvent: NSEvent) {
}
for the click event.
This is the action to which it should reference when a textfield is pressed:
func myAction(sender: NSView)
{
print("aktuell: \(sender)")
currentObject = sender
}
For buttons it is working with the action and selector but this does not work for textfields...
button.action = #selector(myAction)
Please give examples only in swift, I know that there are plenty of examples in obj.-c. Thanks!
Got it working with that:
1) Create a subclass of NSTextField.
import Cocoa
class MyTextField: NSTextField {
override func mouseDown(theEvent:NSEvent) {
let viewController:ViewController = ViewController()
viewController.textFieldClicked()
}
}
2) With Interface building, select the text field you want to have a focus on. Navigate to Custom Class on the right pane. Then set the class of the text field to the one you have just created.**
3) The following is an example for ViewController.
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
func textFieldClicked() -> Void {
print("You've clicked on me!")
}
}

Check if the u key is pressed Swift Cocoa [duplicate]

This question already has answers here:
Swift - Capture keydown from NSViewController
(5 answers)
Closed 6 years ago.
I'm trying to detect if the U key is pressed or not, and if it is it should print("BUT...BUT.."); but I'm not sure how to check for different keys, as the documentation for key presses is quite bad.. I found an answer with keycodes but they only work for QWERTY keyboards
viewcontroller.swift
override func viewDidLoad(){
super.viewDidLoad();
let f = Foo();
f.doSonethimg();
}
override func keyDown(theEvent: NSEvent){
let f = Foo();
f.KeyDown(theEvent);
}
Foo.swift
public func doSonething(){
print("Hello from Dylib");
}
public func keyDown(event: NSEvent){
if let keyString = theEvent.charactersIgnoringModifiers where keyString == "u" || keyString == "U" {
Swift.print("BUT...BUT…")
}
}
How would I change the keyDown Function to respond to U and what is it's default key?
I've looked at - Detecting key press event in Swift and https://superuser.com/questions/399430/mouse-button-and-keypress-counter-for-mac-os-x
also see - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html - Overriding the keyDown: Method
You can easily check for a character by using NSEvents charactersIgnoringModifiers property.
func keyDown(theEvent: NSEvent) {
if let keyString = theEvent.charactersIgnoringModifiers where keyString == "u" || keyString == "U" {
Swift.print("BUT...BUT…")
}
}
Note: There is a difference between checking for 'u' and 'U'. They are modified by Shift. So if you want to have both recognized, check for both. (as in the example above)
Responder Chain:
The keyDown function is only called when the view or viewController participates in the so called Responder Chain.
To set up your viewController for being part of the Responder Chain, read the following documentation.

Capture Global Keydown Events (not simply observe)

I've created some global hotkeys. However using addGlobalMonitorForEventsMatchingMask I can only observe keydown events. What if I want to capture the event and prevent other applications from receiving it?
Here's what I have for observing keydown events:
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
NSEvent.addGlobalMonitorForEventsMatchingMask(.KeyDownMask, handler: keyDown)
NSEvent.addLocalMonitorForEventsMatchingMask(.KeyDownMask) { (event) -> NSEvent! in
self.keyDown(event)
return event
}
}
func keyDown(event : NSEvent) {
if event.modifierFlags.contains(.ControlKeyMask) && event.modifierFlags.contains(.AlternateKeyMask) && event.modifierFlags.contains(.CommandKeyMask) && event.keyCode == 126 {
print("⌃⌥⌘↑ pressed")
}
}
}
I'm not sure where to start to capture keydown events. Any help would be great. Thanks.
DDHotKey allows you to capture keydown events and use them to trigger function in you app. I discovered it recently in this post. If you don't already know how to integrate Objective-C code into a Swift project, you can find the Apple documentation here.