设置从.NET剪贴板时CLIPBRD_E_CANT_OPEN错误剪贴板、错误、NET、CLIPBRD_E_CANT_OPEN

2023-09-04 00:13:21 作者:会哭的礼物

为什么以下code有时会发生与内容CLIPBRD_E_CANT_OPEN异常:

Why does the following code sometimes causes an Exception with the contents "CLIPBRD_E_CANT_OPEN":

Clipboard.SetText(STR);

Clipboard.SetText(str);

这通常发生在第一时间剪贴板中使用的应用和不之后

This usually occurs the first time the Clipboard is used in the application and not after that.

推荐答案

其实,我觉得这是fault的Win32 API的。

要设置数据在剪贴板,你必须打开第一。只有一个进程可以有剪贴板中同时打开。所以,当你检查,如果另一进程在打开剪贴板的以任何理由的,你试图打开它将会失败。

To set data in the clipboard, you have to open it first. Only one process can have the clipboard open at a time. So, when you check, if another process has the clipboard open for any reason, your attempt to open it will fail.

这只是恰巧,终端服务跟踪剪贴板中,并在旧版本的Windows(pre-Vista的),你要打开剪贴板,看看里面有什么......这最终阻止你。唯一的解决办法是等待,直到终端服务关闭剪贴板,然后重试。

It just so happens that Terminal Services keeps track of the clipboard, and on older versions of Windows (pre-Vista), you have to open the clipboard to see what's inside... which ends up blocking you. The only solution is to wait until Terminal Services closes the clipboard and try again.

重要的是要认识到,这不是具体到终端服务,虽然:它可以与任何事情发生。在Win32的剪贴板工作是一个巨大的竞争条件。但是,因为在设计你只应该淤泥与周围响应用户输入剪贴板,这通常并不present一个问题。

It's important to realize that this is not specific to Terminal Services, though: it can happen with anything. Working with the clipboard in Win32 is a giant race condition. But, since by design you're only supposed to muck around with the clipboard in response to user input, this usually doesn't present a problem.