最近在維護WPF系統的時候發現的問題,剛剛開始自己的電腦都不能重現,后面寫日志跟蹤才發現問題的所在。問題主要是由於:1.
在程序訪問剪切板的時候,有其他程序正在占用剪切板,導致自己的程序無法訪問,從而拋出異常;2.沒有訪問的權限,導致自己的程序無法訪問。
以下是報錯的截圖和寫日志跟蹤出來的異常詳細信息截圖:
這個是之前在App.xaml.cs文件中的寫法:
#region
///// <summary>
///// 處理異常的方法
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
//在wpf中如果復制沒有權限此時也會進來這里(PS:以管理員和兼容性運行此程序即可哦)
if (e.Exception.InnerException.Message.Contains("網絡") || e.Exception.InnerException.Message.Contains("超時") || e.Exception.InnerException.Message.Contains("暫停"))
{
BugReport report = new BugReport(e.Exception);
report.Save();
e.Handled = true;
report.LaunchBugReport();
MessageBox.Show(e.Exception.InnerException.Message);
}
else
{
BugReport report = new BugReport(e.Exception);
report.Save();
report.LaunchBugReport();
e.Handled = true;
Application.Current.Shutdown();
}
}
這個是修改之后的寫法:
在App.xaml文件中添加下面代碼中紅色的部分
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml"
DispatcherUnhandledException="Application_DispatcherUnhandledException">
在App.xaml.cs文件中添加代碼:
private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
var comException = e.Exception as System.Runtime.InteropServices.COMException;
if (comException != null && comException.ErrorCode == -2147221040)
e.Handled = true;
BugReport report = new BugReport(e.Exception);
report.Save();
e.Handled = true;
}
這種方法中剪切板動作會自動多次嘗試,由於拋出的異常被App中的異常處理給截獲了,所以會不斷的嘗試直到成功。(PS:以上只是個人的看法,有不當之處,煩請指正。謝謝!)