Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cocoa: menu bar item with backspace as key equivalent

I would like to set the key equivalent of a menu bar item in IB to the backspace key (delete left of the cursor), but for some reason this doesn't seem to work. I can assign all kinds of keys to it, such as CMD+Backspace, or fn+Backspace (delete key, ie delete from right), but when I assign the plain backspace key, it just doesn't register at all.

Do I have to do something different to use the backspace key?

PS: I do not want to handle the key any other way. It must be a menu item key equivalent.

EDIT: I set the key equivalent for the menu item using IB. I know I said that before, but some people can't read. I know how to set it in IB, and it works for everything but the backspace key.

like image 706
mtmurdock Avatar asked Apr 26 '12 04:04

mtmurdock


3 Answers

Please refer to the description of setKeyEquivalent: method in the NSMenuItem Class Reference:

If you want to specify the Backspace key as the key equivalent for a menu item, use a single character string with NSBackspaceCharacter (defined in NSText.h as 0x08) and for the Forward Delete key, use NSDeleteCharacter (defined in NSText.h as 0x7F). Note that these are not the same characters you get from an NSEvent key-down event when pressing those keys.

By the way, I can normally set the Key Equivalent for menu items to backspace in Interface Builder by pressing it and it worked in my sample app (created from Xcode template, set key equivalent of File-Close to backspace). I am using Xcode 4.2 on Snow Leopard. Are there any key binding conflicts in your scenario?

like image 74
Hailei Avatar answered Nov 03 '22 01:11

Hailei


This is old, but I had the same problem and it was killing me. Turns out when I was setting the keyDown handler, I was not calling super.keyDown(theEvent) at the end. Somehow multiple-key shortcuts (like cmd+delete) still fired the events, but the single-character backspace key did not.

This fixed it:

override func keyDown(theEvent: NSEvent) {
    ...
    super.keyDown(theEvent)
}
like image 40
Chase Finch Avatar answered Nov 03 '22 01:11

Chase Finch


Use "\u{08}" for key equivalent string, it works

menu=NSMenuItem(title: "Delete Note", action: nil, 
     keyEquivalent: "\u{08}")

I find this from

let menu=window!.menu
print(menu?.item(at: 1)?.submenu?.item(at: 1)?.keyEquivalent)//set Delete key from xib file

also NSBackspaceCharacter has keycode 8

menu=NSMenuItem(title: "Delete Note", action: nil, 
     keyEquivalent: String(Unicode.Scalar(NSBackspaceCharacter)!))
like image 32
강민석 Avatar answered Nov 03 '22 01:11

강민석