Search code examples
c#.netwinformstoolstripmousecapture

Disable mouse capturing by Button


I create custom ContextMenuStrip with Button in it:

ContextMenuStrip _contextMenu = new ContextMenuStrip();
_contextMenu.Items.Add(new ToolStripMenuItem("Item"));
_contextMenu.Items.Add(new ToolStripControlHost(new Button()));

When I open this context menu and move mouse over 'Item' it is highlighted. But after I clicked Button and then move mouse over 'Item' again it isn't highlighted anymore. Looks like Button captures mouse. How can I avoid this or release capturing after Button clicking?


Solution

  • You can create your own button class inherited from Button and set ControlStyles.Selectable to false, this will prevent it from taking focus:

    public class MyButton : Button
    {
        public MyButton()
        {
            SetStyle(ControlStyles.Selectable, false);
        }
    }
    

    And then just use it instead of Button:

    _contextMenu.Items.Add(new ToolStripControlHost(new MyButton()));