2017-03-21 33 views
-1

我有一個C#窗口,只是發現在Windows 7下的任務欄上右鍵單擊關閉事件沒有被解僱。WPF關閉事件沒有在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(); 
} 

功能OnClosing在Windows 10下叫,但不是在Windows 7在Windows 7中,右鍵單擊並關閉無法關閉我的窗戶。

UPDATE:

今天我也試過在醒目的的WndProc消息WM_CLOSE()。

在Windows 10中,[X]按鈕和右擊任務欄上的關閉都會收到WM_CLOSE消息。 在Windows 7中,只有[X]按鈕收到WM_CLOSE消息。

我在哪裏做錯了嗎?

回答

0

嘗試從碼附加的事件,而不是從XAML:

this.Closing += OnClosing; 

對我來說這是雙向對Windows 7和10

希望這將與您合作。

+0

我在代碼中添加了關閉事件,但仍未在任務欄右鍵單擊的Windows 7中觸發。 – Dia

+0

嘗試使用Closed事件來查看它是否被觸發或是相同的情況 –

+0

封閉事件的行爲相同。 – Dia

0

管理應用程序類

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

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

我使用'Window'類,真的需要'Application'類嗎? – Dia

+0

好吧,它沒有任何成本,並允許您管理不會通過主窗口,如ALT + F4,....看看這個良好的示例:-) http://wfpbookreader.codeplex.com/SourceControl/latest# CBR/CBR/Views/MainView.xaml – GCamel

+0

奇怪的是,Application.OnExit事件沒有引發,在windows 7中從任務欄右鍵單擊。只有X按鈕有效。 – Dia

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中修復。