ToolStripButton still highlighted when form is disabled/enabled

874 Views Asked by At

I have a WinForms application containing a ToolStrip with ToolStripButtons. Some of the button actions disable the main form while the button action takes place and re-enable it when finished. This is done to make sure the user does not click on other places while the action takes place, and also shows a WaitCursor but that's not relevant to the issue.

If the user clicks on the button and moves the mouse cursor outside of its bounds while the form is disabled, the button remains highlighted (transparent blue) even when re-enabling the form at a later point. If the mouse enter/leaves the button afterwards it is displayed correctly again.

I could artificially replicate the problem by showing a MessageBox using the following code (the actual action does not show a message box, but opens a new form and populates a grid, but the net effect is the same).

Here is a code snippet to replicate the issue:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void toolStripButton1_Click(object sender, EventArgs e)
    {
        // Disable the form
        Enabled = false; 

        // Some action where the user moved the mouse cursor to a different location
        MessageBox.Show(this, "Message");

        // Re-enable the form
        Enabled= true; 
    }
}
1

There are 1 best solutions below

0
Andres On

I finally found a solution.

I created this extension method that uses reflection to call the private method "ClearAllSelections" on the parent toolstrip:

    public static void ClearAllSelections(this ToolStrip toolStrip)
    {
        // Call private method using reflection
        MethodInfo method = typeof(ToolStrip).GetMethod("ClearAllSelections", BindingFlags.NonPublic | BindingFlags.Instance);
        method.Invoke(toolStrip, null);
    }

and call it after re-enabling the form:

private void toolStripButton1_Click(object sender, EventArgs e)
{
    // Disable the form
    Enabled = false; 

    // Some action where the user moved the mouse cursor to a different location
    MessageBox.Show(this, "Message");

    // Re-enable the form
    Enabled= true;

    // Hack to clear the button highlight
    toolStrip1.ClearAllSelections();
}