B.K.
B.K.

Reputation: 10162

Button control keeps flashing after it has been clicked and handled the event

This is related to WPF and C#. I have several buttons in my program and when they're being clicked, they'll keep on flashing even after handling an event. For example, of the buttons that I have is supposed to open a new window based on the user input. If the user's input is incorrect and MessageBox will come up saying so. Once I close the MessageBox, button begins flashing. If the user input is correct, the new window will open. Once I click away from the new window into the old window, button begins to flash; if I close the new window, button begins to flash.

I tried using this.Focus() all over my code that concerns this button to get the focus on the main window. I tried using e.Handled = true, but nothing seems to stop it. I don't want to make the button not Focusuable by setting that property to false, because I want my program to be accessible.

Any ideas what's going on?

Here's my XAML code for the button:

<Button x:Name="btnSearch" Content="Search" Background="#4a89be" Foreground="White"
        MouseEnter="Button_MouseEnter" MouseLeave="Button_MouseLeave"
        Click="btnSearch_Click" />

C# code for the button (this doesn't have this.Focus() because it didn't work for me):

private void btnSearch_Click(object sender, RoutedEventArgs e)
{
    if (!String.IsNullOrEmpty(txtNumber.Text.ToString()) && txtNumber.Text.ToString().Length >= 10)
    {
        if (QueryWindow == null)
        {
            QueryWindow = new DatabaseQueryWindow();
            QueryWindow.Show();
            QueryWindow.Closed += new EventHandler(QueryWindow_Closed);
        }
        else if (QueryWindow != null && !QueryWindow.IsActive)
        {
            QueryWindow.Activate();
        }

            QueryDB();
        }
   else
   {
       MessageBox.Show("Please enter a valid # (Format: YYYYmm####)");
   }
}

void QueryWindow_Closed(object sender, EventArgs e)
{
    QueryWindow = null;
}


private void Button_MouseEnter(object sender, MouseEventArgs e)
{
    Button b = sender as Button;
    if (b != null)
    {
        b.Foreground = Brushes.Black;
    }
}
private void Button_MouseLeave(object sender, MouseEventArgs e)
{
    Button b = sender as Button;
    if (b != null)
    {
        b.Foreground = Brushes.White;
    }
}

Upvotes: 0

Views: 2061

Answers (1)

B.K.
B.K.

Reputation: 10162

For anyone interested in how to get rid of this behavior without disabling focus on buttons:

After an action is executed, just redirect focus to another control, such as a textbox that's next to a button: txtBox.Focus();

Worked for me. I wasn't able to find another simple way.

Upvotes: 2

Related Questions