如何处理被阻止的剪贴板和其他问题 [英] How to handle a blocked clipboard and other oddities

查看:355
本文介绍了如何处理被阻止的剪贴板和其他问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几个小时中,我一直在追踪一个相当具体的错误,因为另一个应用程序打开了剪贴板,所以发生了这个错误。本质上,剪贴板是共享资源(根据为什么我的共享剪贴板不起作用? ),您尝试执行

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().

抛出以下异常:


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包含用于次数和延迟时间的字段。 .NET的默认行为是尝试10次,并延迟100毫秒。

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. .NET's default behaviour is to try 10 times with a 100 msec 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是合理的。如果将SetObjectData调用写入剪贴板失败,我建议向用户显示错误。

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 an error to the user if the SetObjectData call to write to the clipboard fails.

建议使用(通过 P / Invoke user32!GetOpenClipboardWindow 查看其他应用程序是否已打开剪贴板。它将返回打开剪贴板的窗口的HWND,如果没有打开应用程序,则返回 IntPtr.Zero 。您可以旋转该值直到其 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 its IntPtr.Zero for a specified amount of time.

这篇关于如何处理被阻止的剪贴板和其他问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆