剪贴板操作失败

背景

使用Clipboard.SetText()向剪贴板写入字符串时,偶尔会引发System.Runtime.InteropServices.ExternalException异常,异常信息如下:

说明: 由于未经处理的异常,进程终止。
异常信息: System.Runtime.InteropServices.ExternalException
   在 System.Windows.Forms.Clipboard.ThrowIfFailed(Int32)
   在 System.Windows.Forms.Clipboard.SetDataObject(System.Object, Boolean, Int32, Int32)
   在 System.Windows.Forms.Clipboard.SetText(System.String, System.Windows.Forms.TextDataFormat)
   在 System.Windows.Forms.Clipboard.SetText(System.String)

问题

由于剪贴板是系统的公共资源,当有多个程序同时访问时,会引发异常。

方案

可以使用Clipboard.SetDataObject()方法代替Clipboard.SetText(),并设置重试次数与重试间隔:

Clipboard.SetDataObject(text, true, 10, 200);

posted @ 2019-04-29 13:13  weca  阅读(3564)  评论(1编辑  收藏  举报