处理LostFocus和停用事件

时间:2011-05-14 07:12:13

标签: .net wpf

我已将此代码附加到LostFocusDeactivate个事件:

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

奇怪的空白catch导致了这样一个事实,即如果我关闭(通过按X)窗口,它也会引发Deactivate,即便如此,我也试图关闭关闭窗口。有没有更好的方法来处理它?<​​/ p>

为了更清楚,我的方案是:我有一个窗口需要关闭lostfocus,停用和关闭常规XAlt+f4

2 个答案:

答案 0 :(得分:5)

另一个选项(除了具有IsClosing状态)是附加到结束事件并取消订阅已停用和失去的焦点事件以防止它们被调用:

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

答案 1 :(得分:1)

您可以尝试这样的事情:

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