2016-11-28 46 views
1

我有一個包含ToolStripButtons的ToolStrip的WinForms應用程序。某些按鈕操作會在按鈕操作發生時禁用主窗體,並在完成後重新啓用它。這是爲了確保用戶在動作發生時不會點擊其他地方,並且還顯示一個WaitCursor,但這與問題無關。ToolStripButton在表單被禁用/啓用時仍然突出顯示

如果用戶單擊該按鈕並在禁用表單時將鼠標光標移動到邊界之外,即使在稍後重新啓用表單時,該按鈕仍保持突出顯示(透明藍色)。如果鼠標進入/離開按鈕後再次正確顯示。

我可以通過使用以下代碼顯示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; 
    } 
} 
+0

你有沒有嘗試添加'this.Refresh();'作爲'toolStripButton1_Click'中的第一行? – ispiro

+0

我現在試過你的代碼,當我關閉MessageBox時,藍色背景消失。 – ispiro

+0

@ispiro試着用'this.Refresh();'但問題仍然存在。也許你用Enter鍵關閉了MessageBox而不是用鼠標點擊?不確定它是否相關,但我正在使用Visual Studio 2013和.NET Framework 4.5。 – Andres

回答

2

我終於找到了解決辦法。

我創建了一個使用反射來調用父工具條的私有方法「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(); 
} 
相關問題