如何处理“锁定"剪贴板 [英] How to deal with "locked" clipboard

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

问题描述

大家好,

我已经编写了一些应用程序,旨在使用户能够通过运行应用程序或单击应用程序GUI中的元素将文本复制到剪贴板.在大多数情况下,这非常正常:

Hello all,

I''ve written a few applications which are meant to enable the user to copy text to their clipboard either just by running the application or by clicking on an element in the application GUI. Most of the time, this works perfectly fine:

public static void grab(string text)
{
    Clipboard.SetDataObject(text, true);
}



但是,有时会弹出一个讨厌的.NET异常对话框.我希望我已经截图了;但要点是剪贴板已锁定&无法写入.

为了解决这个问题,我想出了一种快速肮脏的暴力解决方案,但我对此并不完全满意:



Once in a while, however, a nasty .NET exception dialog would pop up. I wish I had taken a screenshot; but the gist of it was that the clipboard was locked & couldn''t be written to.

In order to handle this, I came up with a quick-and-dirty brute force solution that I''m not entirely happy with:

public static void grab(string text)
    {
        grab(text, 0);
    }

private static void grab(string text, int attempt)
    {
        //if no luck after 6 tries, give up.
        if (attempt > 5)
            return;

        try
        {
            Clipboard.SetDataObject(text, true);
        }

        catch (Exception) 
        {
            //Wait half a second, increment attempt counter and then try again
            System.Threading.Thread.Sleep(500);
            grab(text, ++attempt);
        }
    }



这似乎在大多数时候都有效,但是它不是很优雅,也不是万无一失,我想知道是否有人知道有更好的方法来解决这个问题.



This appears to work most of the time, but its not very elegant nor is it foolproof, and I was wondering if anyone knows of a better way to deal with this.

Thanks in advance!

推荐答案

请参阅我对问题的评论.

我立即看到的一个问题是:由于您的对象始终是字符串,因此应使用Clipboard.SetText http ://msdn.microsoft.com/en-us/library/ydby206k.aspx [ ^ ].

另一方面,如果此字符串带有某种特殊的语义(因此,这是一些自定义对象,而字符串只是一种媒体),则应注册一种自定义数据格式. (或者您已经这样做了吗?)此CodeProject文章介绍了涉及的技术:
使用.NET进行剪贴板处理-第II部分 [
Please see my comment to the question.

One problem I can see immediately is: as your object is always a string, you should use Clipboard.SetText, http://msdn.microsoft.com/en-us/library/ydby206k.aspx[^].

From the other hand, if this string carries some special semantic (so, this is some custom object and string is just a media), you should register a custom data format. (Or do you do this already?) This CodeProject article explains the techniques involved:
Clipboard handling with .NET - Part II[^].

—SA


这篇关于如何处理“锁定"剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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