WPF复制异常问题(OpenClipboard 失败 (异常来自 HRESULT:0x800401D0 (CLIPBRD_E_CANT_OPEN)))

   最近在维护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:以上只是个人的看法,有不当之处,烦请指正。谢谢!)


原文地址:https://www.cnblogs.com/sexintercourse/p/6897829.html