在Windows 7中没有触发WPF Closing事件?

时间:2017-03-21 06:25:04

标签: c# wpf

我有一个C#窗口,发现Windows 7下任务栏上的右键单击关闭事件未被触发。

enter image description here

然而,在我开发的Windows 10 PC上,此操作已正确处理。 我的xaml文件如下所示:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WCSevenX"
    x:Class="WCSevenX.MainWindow"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"                
    Loaded="Window_Loaded" 
    Closing="OnClosing"  
    Background="#B0CBCBE5" 
    Name="MainWnd" 
    Unloaded="MainWnd_Unloaded" 
    SizeChanged="MainWnd_SizeChanged" 
    PreviewGotKeyboardFocus="MainWnd_PreviewGotKeyboardFocus" 
    PreviewLostKeyboardFocus="MainWnd_PreviewLostKeyboardFocus" 
    GotFocus="MainWnd_GotFocus" 
    GotKeyboardFocus="MainWnd_GotKeyboardFocus">
    <!--body...-->
</Window>

OnClosing功能是:

private void OnClosing(object sender, CancelEventArgs e)
{
    //do something before close
    //...
    //close my window
    System.Windows.Application.Current.Shutdown();
    System.Diagnostics.Process.GetCurrentProcess().Kill();
}

在Windows 10下调用函数OnClosing,但在Windows 7中不调用。在Windows 7中,右键单击并关闭无法关闭窗口。

更新

今天我也尝试在WndProc()中捕获WM_CLOSE消息。

在Windows 10中,任务栏上的[X]按钮和右键单击关闭都会收到WM_CLOSE消息。 在Windows 7中,只有[X]按钮收到WM_CLOSE消息。

我做错了吗?

3 个答案:

答案 0 :(得分:1)

尝试从代码中附加事件,而不是从xaml:

 this.Closing += OnClosing;

对我而言,这适用于Windows 7和10。

希望这对你有用。

答案 1 :(得分:0)

管理应用程序类中的退出事件

protected override void OnExit(ExitEventArgs e)
    {
        base.OnExit(e);

        this.DispatcherUnhandledException -= new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
    }

答案 2 :(得分:0)

我发现我有一个有调度员的线程:

private void StartDlg()
{
    wnd = new MyDlg();
    wnd.Show();
    Dispatcher.Run();  //<-this start an event loop
}
Thread myThread = new Thread(StartDlg);

经过一番搜索,我知道如果我不这样做

Dispatcher.FromThread(myThread).InvokeShutdown();

我的线程将阻止窗口消息循环。

在Windows 8+中它很好,但在Windows 7中,这将阻止右键单击关闭消息以传递到我的应用程序。添加InvokeShutdown将在Windows 7中修复。

相关问题