0

I am writing a menu extra in Swift that brings up a window for the user to enter some data. It would be handy to have the copy an paste keyboard shortcuts for this window.

I have added an edit submenu to my menu extra so that I and defined the keyboard shortcuts. I have linked them to methods in my controller, but when type the shortcut command such as command-v, it does not call the associated method.

How should I go about enabling the shortcuts for the menu extra?

zorro2b
  • 2,227
  • 4
  • 28
  • 45

1 Answers1

1

I don't know if this is the right way to do it, but I managed to get it working based on the approach in this post: Cocoa Keyboard Shortcuts in Dialog without an Edit Menu

I created a similar MyApplication class and also linked the copy, paste etc actions of first responder to my menus.

I had some trouble getting the syntax right for the latest swift. Here is the code I used:

import Cocoa

class MyApplication: NSApplication {
    override func sendEvent(event: NSEvent) {
        if event.type == NSEventType.KeyDown {

            if ((event.modifierFlags.rawValue) & (NSEventModifierFlags.CommandKeyMask.rawValue) > 0) {
                switch event.charactersIgnoringModifiers!.lowercaseString {
                case "x":
                    if NSApp.sendAction(Selector("cut:"), to:nil, from:self) { return }
                case "c":
                    if NSApp.sendAction(Selector("copy:"), to:nil, from:self) { return }
                case "v":
                    if NSApp.sendAction(Selector("paste:"), to:nil, from:self) { return }
                case "z":
                    if NSApp.sendAction(Selector("undo:"), to:nil, from:self) { return }
                case "a":
                    if NSApp.sendAction(Selector("selectAll:"), to:nil, from:self) { return }
                default:
                    break
                }
            }
        }
        return super.sendEvent(event)
    }
}
Community
  • 1
  • 1
zorro2b
  • 2,227
  • 4
  • 28
  • 45