1

我有一个 WinForms 应用程序,其中包含一个带有 ToolStripButtons 的 ToolStrip。一些按钮操作会在按钮操作发生时禁用主窗体,并在完成后重新启用它。这样做是为了确保用户在操作发生时不会单击其他位置,并且还会显示 WaitCursor 但这与问题无关。

如果用户在表单被禁用时单击按钮并将鼠标光标移到其边界之外,则即使稍后重新启用表单,该按钮也会保持突出显示(透明的蓝色)。如果之后鼠标进入/离开按钮,它会再次正确显示。

我可以通过使用以下代码显示 MessageBox 来人为地复制问题(实际操作不会显示消息框,而是打开一个新表单并填充一个网格,但最终效果是相同的)。

这是一个复制问题的代码片段:

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; 
    }
}
4

1 回答 1

3

我终于找到了解决方案。

我创建了这个扩展方法,它使用反射在父工具条上调用私有方法“ClearAllSelections”:

    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);
    }

并在重新启用表单后调用它:

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();
}
于 2016-11-29T17:05:00.130 回答