2016-11-28 8 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

はあなたをしました'toolStripButton1_Click'の最初の行に' this.Refresh(); 'を追加してみてください。 – ispiro

+0

私はあなたのコードを試して、私はMessageBoxを閉じると青い背景が消えます。 – ispiro

+0

@ispiro 'this.Refresh();'を試みましたが、それでも問題は発生します。おそらく、あなたはマウスでクリックするのではなく、Enterを使ってMessageBoxを閉じたでしょうか?関連性があるかどうかは不明ですが、Visual Studio 2013と.NET Framework 4.5を使用しています。 – Andres

答えて

2

私が最終的に解決策を見つけました。

私は親ToolStripの上のプライベートメソッド「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(); 
} 
関連する問題