【问题标题】:ToolStripButton still highlighted when form is disabled/enabled禁用/启用表单时 ToolStripButton 仍然突出显示
【发布时间】:2016-11-28 18:47:29
【问题描述】:

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

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

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

这里是复制问题的代码 sn-p:

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

【问题讨论】:

  • 您是否尝试将this.Refresh(); 添加为toolStripButton1_Click 的第一行?
  • 我现在尝试了你的代码,当我关闭 MessageBox 时蓝色背景消失了。
  • @ispiro 尝试使用this.Refresh();,但问题仍然存在。也许您用 Enter 关闭了 MessageBox 而不是用鼠标单击?不确定它是否相关,但我使用的是 Visual Studio 2013 和 .NET Framework 4.5。
  • 鼠标和“Enter”都可以正常工作。我正在使用 VS2015(64 位 Windows 10)。我还将它转换为 .net 4.5(从 4.5.2 开始),它仍然可以正常工作。我不知道可能有什么不同。祝你好运。
  • ToolStripButton 在没有任何帮助的情况下很好地使自己看起来被禁用。你可能做错了什么并不那么明显,但没有为按钮选择好的位图必须是根本问题。

标签: c# forms winforms toolstrip toolstripbutton


【解决方案1】:

我终于找到了解决办法。

我创建了这个扩展方法,它使用反射来调用父工具条上的私有方法“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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    相关资源
    最近更新 更多