Is there any way to show a menu when a NSWindow is right-clicked?
Asked
Active
Viewed 3,373 times
2 Answers
18
Rightclick on a view in the window and you will find a property called "menu". Connect this menu property with the menu which should be shown after a right click.

Peter Hosey
- 95,783
- 15
- 211
- 370

lbrndnr
- 3,361
- 2
- 24
- 34
-
8In case you see this in your inbox later and wonder how people are upvoting an answer you deleted: I edited your answer to fix the one inaccuracy, and called on fellow Stack Overflow users who follow me on Twitter to cast votes to undelete it. After I and two others cast such votes, your now-correct answer became undeleted. – Peter Hosey Feb 25 '11 at 23:21
3
Yes. NSWindow
inherits from NSResponder
, which has handy methods like -rightMouseDown:
.
edit
Actually a better way to do it might be to use a custom NSView
subclass for the window's contentView
, and override -menuForEvent:
(a method on NSView
) to return your right-click menu with the passed NSEvent
is a right-click event.

Dave DeLong
- 242,470
- 58
- 448
- 498
-
Ok, that's good. How would I make a NSMenu visible just at the point where the user had right clicked though? – Seb Jachec Feb 25 '11 at 18:34
-
I'm hopeless at this... Is this right? Where do I go from here? - (void)menuForEvent:(NSEvent *)event, then I put if (event == NSRightMouseDown) – Seb Jachec Feb 25 '11 at 19:08
-
@magikseb: yep, that looks about right (though the method sure not be `-(void)...` but rather `-(NSMenu *)...`) – Dave DeLong Feb 25 '11 at 19:33
-
I'm sorry. I just really don't understand this. Do I have to pass in an NSMenu as input? What do I do inside the method? :S – Seb Jachec Feb 25 '11 at 21:17
-
1Don't override either of those methods. Set the view's `menu`, and the view will do the right thing for you. You don't even need to subclass NSView to do that. – Peter Hosey Feb 25 '11 at 22:25
-
1I see a downvote—seems somebody took my comment a little too far. Sorry about that. To be fair, Dave's answer will work, and `menuForEvent:` is the correct solution when you need to customize or choose the menu on demand; all I'm saying is that when you don't, it's easier to simply set the menu in the nib (or at run time if necessary). – Peter Hosey Feb 26 '11 at 02:04