Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to toggle a ContextMenuStrip display using a button click but also allowing it to close normally (menu item clicks, lost focus etc)
    primarykey
    data
    text
    <p>I created a simple UserControl consisting of a Label and ContextMenuStrip. I made it function like a ComboBox but instead of a dropdown I'm displaying a ContextMenuStrip. </p> <p>I have it working but there's some trickiness that I can't figure out. </p> <p>I'm trying to make the label ComboButton work the same way a ComboBox does. Click the button, the dropdown appears. Click the button a second time and it'll retract. The problem is, the ContextMenu disappears on any mouse click. So when I click the button a second time to retract the menu, the menu disappears first, and then the click event fires, displaying the menu again.</p> <p>I still want the Menu to disappear when a user selects a menuitem and when they just click anywhere on the form like a normal context menu does.</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing.Drawing2D; using System.Windows.Forms.VisualStyles; using System.Diagnostics; namespace Controls { public partial class CMenu : UserControl { ButtonState _buttonState = ButtonState.Normal; public CMenu() { InitializeComponent(); } private void lblSelect_Paint(object sender, PaintEventArgs e) { base.OnPaint(e); ControlPaint.DrawComboButton(e.Graphics, getLabelRect(), _buttonState); } private bool IsDropdownHit(MouseEventArgs e) { Rectangle cursor = new Rectangle(e.X, e.Y, 1, 1); if (e.Button == MouseButtons.Left &amp;&amp; cursor.IntersectsWith(getLabelRect())) { return true; } return false; } private void lblSelect_MouseUp(object sender, MouseEventArgs e) { if (!IsDropdownHit(e)) return; if (!cmsItems.Visible) lblSelect.ContextMenuStrip = cmsItems; cmsItems.Width = lblSelect.Width; cmsItems.Show(lblSelect, 0, lblSelect.Height); } private Rectangle getLabelRect() { return new Rectangle(lblSelect.Width - 20, 0, 20, lblSelect.Height); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload