I'm developing simple C# application using Windows.Forms on .NET. I need some button that will show a drop-down menu with subcategories - much like ToolStripMenu, but the button, you know. I searched for it and could not found any variants.
My question is: is there any way to do this, maybe some secret button property that allows attach menu to it?
Any help will be appreciated.
Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the ComboBox control to set the DropDownStyle property of the ComboBox.
To create a drop-down button: Select the UltraDropDownButton element from the Visual Studio toolbox and double-click it, drag it on to the form, or click it and draw the element onto the form. Add a second control that will displayed when the drop-down button is clicked.
Button have down arrow right side of it and you can set menu of it from designer:
With ShowMenuUnderCursor:
MenuButton class:
public class MenuButton : Button { [DefaultValue(null)] public ContextMenuStrip Menu { get; set; } [DefaultValue(false)] public bool ShowMenuUnderCursor { get; set; } protected override void OnMouseDown(MouseEventArgs mevent) { base.OnMouseDown(mevent); if (Menu != null && mevent.Button == MouseButtons.Left) { Point menuLocation; if (ShowMenuUnderCursor) { menuLocation = mevent.Location; } else { menuLocation = new Point(0, Height); } Menu.Show(this, menuLocation); } } protected override void OnPaint(PaintEventArgs pevent) { base.OnPaint(pevent); if (Menu != null) { int arrowX = ClientRectangle.Width - 14; int arrowY = ClientRectangle.Height / 2 - 1; Brush brush = Enabled ? SystemBrushes.ControlText : SystemBrushes.ControlDark; Point[] arrows = new Point[] { new Point(arrowX, arrowY), new Point(arrowX + 7, arrowY), new Point(arrowX + 3, arrowY + 4) }; pevent.Graphics.FillPolygon(brush, arrows); } } }
You can show the ContextMenuStrip on the click event:
private void button1_Click(object sender, EventArgs e) { contextMenuStrip1.Show(button1, new Point(0, button1.Height)); }
To make your own determination whether to show the menu above or below the button, you can try using this code, which measures the menu and determines whether or not it would be partially offscreen:
private void button1_Click(object sender, EventArgs e) { Point screenPoint = button1.PointToScreen(new Point(button1.Left, button1.Bottom)); if (screenPoint.Y + contextMenuStrip1.Size.Height > Screen.PrimaryScreen.WorkingArea.Height) { contextMenuStrip1.Show(button1, new Point(0, -contextMenuStrip1.Size.Height)); } else { contextMenuStrip1.Show(button1, new Point(0, button1.Height)); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With