zerkms
zerkms

Reputation: 254886

Handling LostFocus and Deactivate events

I have this code attached to LostFocus and Deactivate events:

    private void Window_LostFocus(object sender, EventArgs e)
    {
        try
        {
            this.Close();
        }
        catch (InvalidOperationException ex) { }
    }

Weird blank catch is caused the fact, that if I close (by pressing X) the window it also raises Deactivate even so in this case I'm trying to close already closing window. Is there any better way to handle it?

To be more clear, my scenario is: I have a window that needed to be closed on lostfocus, deactivation and closing with regular X or Alt+f4.

Upvotes: 1

Views: 1245

Answers (2)

ChrisWue
ChrisWue

Reputation: 19020

Another option (besides having an IsClosing state) is to attach to the closing event and unsubscribe from the deactivated and lost focus events to prevent them from being called:

private void Window_Closing(object sender, EventArgs e)
{
    Deactivated -= Window_Deactivated;
    LostFocus -= Window_LostFocus;
}

Upvotes: 5

Henk van Dijken
Henk van Dijken

Reputation: 249

You could try something like this:

bool IsClosing = false;
private void Window_LostFocus(object sender, RoutedEventArgs e)
{
    CloseWindow();
}

private void Window_Deactivated(object sender, EventArgs e)
{
    CloseWindow();
}

void CloseWindow()
{
    if (IsClosing == false)
    {
        IsClosing = true;
        this.Close();
    }
}

Upvotes: 1

Related Questions