我开发一个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)文件状态*当应用程序抛出异常但未处理时发生* –