Last active
January 23, 2018 19:58
-
-
Save CartBlanche/24d925377a6a6d6c5a9207d797ca7b1d to your computer and use it in GitHub Desktop.
How to Popup a Context Menu when NSButton is Clicked in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Taken from https://praveenmatanam.wordpress.com/2008/09/05/how-to-popup-context-menu-when-clicked-on-button/ and converted to C# | |
where... | |
propertyButton is NSButton. | |
popUpContextMenu is a prepopulated NSMenu with NSMenuItems | |
propertyButton.Activated += (object sender, EventArgs e) => { | |
var senderAsButton = (NSButton)sender; | |
var frame = senderAsButton.Frame; | |
var menuOrigin = senderAsButton.Superview.ConvertPointToView (new CGPoint (frame.Location.X, frame.Location.Y + frame.Size.Height + 3), null); | |
var popupMenuEvent = NSEvent.MouseEvent (NSEventType.LeftMouseDown, menuOrigin, (NSEventModifierMask)0x100, 0, senderAsButton.Window.WindowNumber, senderAsButton.Window.GraphicsContext, 0, 1, 1); | |
NSMenu.PopUpContextMenu (popUpContextMenu, popupMenuEvent, senderAsButton); | |
}; | |
Thanks Chris Hamons for your help! | |
And if you want to use a subclass, try something like this... | |
public class ButtonWithContextMenu : NSButton | |
{ | |
NSMenu popUpContextMenu; | |
public NSMenu PopUpContextMenu { | |
get { return popUpContextMenu; } | |
set { popUpContextMenu = value; } | |
} | |
public ButtonWithContextMenu () | |
{ | |
Bordered = false; | |
Enabled = true; | |
Image = NSImage.ImageNamed ("maybe-a-fancy-image-here"); | |
ImageScaling = NSImageScale.AxesIndependently; | |
Title = string.Empty; | |
TranslatesAutoresizingMaskIntoConstraints = false; | |
popUpContextMenu = new NSMenu (); | |
} | |
public override void MouseDown(NSEvent theEvent) | |
{ | |
if (theEvent.Type == NSEventType.LeftMouseDown) { | |
var menuOrigin = this.Superview.ConvertPointToView (new CGPoint (Frame.Location.X - 1, Frame.Location.Y + Frame.Size.Height + 4), null); | |
var popupMenuEvent = NSEvent.MouseEvent (theEvent.Type, menuOrigin, (NSEventModifierMask)0x100, 0, this.Window.WindowNumber, this.Window.GraphicsContext, 0, 1, 1); | |
NSMenu.PopUpContextMenu (popUpContextMenu, popupMenuEvent, this); | |
} | |
base.MouseDown(theEvent); | |
} | |
} | |
Use the PopUpContextMenu property to populate your menu when the time is right for you. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment