WPF中的Main()入口點是從App.xaml源文件自動生成的。儘早您必須訂閱該事件是在構造函數中App.xaml.cs App類:
public partial class App : Application {
public App() {
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
// etc...
}
}
然而,這不是「完美」,你無法探測出你的應用程序類的字段初始化任何故障。除了在您的應用程序類中使用的類型的任何JIT編譯失敗之外,缺少作爲常見麻煩製造者的組件或版本問題。
爲了避免遺漏這些,您需要放棄自動生成的代碼並編寫自己的Main()方法。假設您沒有大量修改app.xaml文件。從項目中刪除該文件,並添加一個新的類,我會建議Program.cs :)並使其看起來類似於:
using System;
using System.Runtime.CompilerServices;
using System.Windows;
namespace WpfApplication1 {
class Program {
[STAThread]
public static void Main(string[] args) {
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Start();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void Start() {
var app = new App();
app.Run(new MainWindow());
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
// etc..
}
}
public class App : Application {
// etc..
}
}
您可以在* app.xaml.cs *中執行此操作。請參閱:[未處理的例外] [1] [1]:http:// stackoverflow。com/questions/2251868 /未處理的異常 – musium
@musium這隻適用於DispatcherUnhandledException。對於'AppDomain.UnhandledException',至少智能感知不顯示相同。 – ispiro
這是WPF中最接近UnhandledException(Winforms)的東西。 請參閱:https://msdn.microsoft.com/en-us/library/system.windows.application.dispatcherunhandledexception%28v=vs.110%29.aspx – musium