如何处理被阻止剪贴板等奇特奇特、剪贴板、如何处理

2023-09-02 01:52:44 作者:邀饮山中霁

在最后几个小时的过程中我一直在追踪一个相当具体的错误有发生,因为另一个应用程序具有打开剪贴板。从本质上讲是剪贴板是一个共享资源(按"Why没有我的共享剪贴板不工作?),并试图执行

Over the course of the last couple of hours I have been tracking down a fairly specific bug with that occurs because another application has the clipboard open. Essentially as the Clipboard is a shared resource (as per "Why does my shared clipboard not work?") and you attempt to execute

Clipboard.SetText(string)

Clipboard.Clear().

下面抛出异常:

The following exception is thrown:


System.Runtime.InteropServices.ExternalException: Requested Clipboard operation did not succeed. 
    at System.Windows.Forms.Clipboard.ThrowIfFailed(Int32 hr)
    at System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, Int32 retryTimes, Int32 retryDelay)
    at System.Windows.Forms.Clipboard.SetText(String text, TextDataFormat format)
    at System.Windows.Forms.Clipboard.SetText(String text)

我最初的解决方案是一个短暂的停顿后重试,直到我意识到Clipboard.SetDataObject具有的次数和延迟的长度字段,.NETs默认行为是尝试10次10​​0毫秒的延迟。

My initial solution was to retry after a short pause, until I realised that Clipboard.SetDataObject has fields for the number of times and the length of the delay, .NETs default behaviour is to try 10 times with 100msec delay.

目前已经注意到了最终用户的最后一件事,那就是尽管抛出异常复制到剪贴板操作仍然有效,我一直没能找到为什么这可能是任何进一步的信息。

There is one final thing that has been noted by the end user, that is despite the exception being thrown the copy to clipboard operation still works, I haven't been able to find any further information about why this may be.

我目前的解决问题的办法就是悄悄忽略例外...这真的是最好的方法是什么?

My current solution to the issue is just to silently ignore the exception... is this really the best way?

推荐答案

由于剪贴板由所有UI应用程序共享,你会遇到这种不时显然,你不想让你的应用程序崩溃,如果它失败了写到剪贴板,所以适当地处理ExternalException是合理的,我建议presenting和错误给用户,如果setobjectdata调用write到剪贴板失败。

As the clipboard is shared by all UI applications, you will run into this from time to time, obviously you don't want your application to crash if it failed to write to the clipboard, so gracefully handling ExternalException is reasonable, i would suggest presenting and error to the user if the setobjectdata call to write to the clipboard fails.

一个建议是使用(通过的P / Invoke)user32!GetOpenClipboardWindow是否有其他应用程序的打开剪贴板,它会返回它具有打开剪贴板,或者 IntPtr.Zero 如果没有应用程序有它打开,你可以在窗口的HWND旋上的值,直到它的 IntPtr.Zero 在指定的时间。

A suggestion would be to use (via p/invoke) user32!GetOpenClipboardWindow to see if another application has the clipboard open, it will return the HWND of the window which has the clipboard open, or IntPtr.Zero if no application had it open, you could spin on the value until it's IntPtr.Zero for a specified amount of time.