我開發一個WPF應用程序中,我已經處理Exception
全球顯示錯誤形式App.xaml.cs。如何在WPF應用程序
對於我已經指MSDN
文件。
並據此我的代碼我的主窗口:
private void TestMethod()
{
string s = null;
try
{
s.Trim();
}
catch (Exception ex)
{
MessageBox.Show("A handled exception just occurred: " + ex.Message, "RestartApplication", MessageBoxButton.OK, MessageBoxImage.Warning);
}
s.Trim();
}
在我App.xaml.cs
public App() : base()
{
this.Dispatcher.UnhandledException += Application_DispatcherUnhandledException;
}
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show("An unhandled exception just occurred: " + e.Exception.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Warning);
e.Handled = true;
}
在這裏,我期待2 MessageBox
一個例外。並且好像沒有調用Application_DispatcherUnhandledException
。
但我怎麼能處理來自App.xaml.cs
錯誤,並顯示消息框VS給出了第二s.Trim();
錯誤?
我已經指的SO像許多鏈接:
dispatcherunhandledexception-does-not-seem-to-work
globally-catch-exceptions-in-a-wpf-application
更新:實時應用程序代碼,被第二個消息框不顯示:
private void ListProcesses()
{
string s = null;
Process[] localByName = Process.GetProcessesByName("notepad++");
DateTime test = new DateTime();
try
{
s.Trim();
foreach (Process p in localByName)
{
this.Dispatcher.Invoke(() =>
{
if (storevalue != p.MainWindowTitle && !String.IsNullOrEmpty(p.MainWindowTitle))
{
aTimer.Stop();
this.Visibility = Visibility.Visible;
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
this.Topmost = true;
this.WindowState = System.Windows.WindowState.Maximized;
this.ResizeMode = System.Windows.ResizeMode.NoResize;
storevalue = p.MainWindowTitle;
}
});
}
}
catch (Exception ex)
{
aTimer.Stop();
MessageBoxResult result = MessageBox.Show("A handled exception just occurred: " + ex.Message, "RestartApplication", MessageBoxButton.OK, MessageBoxImage.Warning);
}
s.Trim();
}
'DispatcherUnhandledException'作爲它的名稱說,是爲了處理異常。看到你的代碼,我會期待一個「剛剛發生的處理的異常」,後面跟着「剛剛發生的未處理的異常」... – Pikoh
@Pikoh,我有[MSDN](https://msdn.microsoft.com/zh-cn/ -us/library/system.windows.application.dispatcherunhandledexception.aspx)文件狀態*當應用程序拋出異常但未處理時發生* –