开发者

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 wind开发者_Go百科ow 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.


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


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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜