剪贴板访问的奇怪性 [英] Strangeness with clipboard access

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

问题描述

我正在尝试编写一个需要使用剪贴板的某些功能的小型应用程序。由于我不想覆盖剪贴板中当前的用户数据,因此决定将其保存到内存中,然后做我的工作,然后再写回去。下面的代码是一个控制台应用程序,是我尝试做的一个准系统示例。

I'm trying to write a small application that needs to use the clipboard for some functionality. Since I don't want to overwrite the user's data currently in the clipboard I decided to save it to memory, do my job and then write it back. The code below is a console application that is a barebones example of what I'm trying to do.

我遇到的问题是恢复状态。如果在运行应用程序之前从Visual Studio将某些内容复制到剪贴板,则剪贴板中共有六个对象(各种字符串格式和语言环境),所有这些对象都放入缓存中。还原它们后,尽管只有区域设置位于剪贴板中,并且似乎对SetData()的每次调用都会覆盖最后一个。 (顺便说一下,SetDataObject似乎不是GetDataObject的逆函数,所以我不能只使用它)

The problem I'm having is restoring the state. If I copy something to the clipboard from Visual Studio before running the application there are a total of six objects in the clipboard (various string formats and a locale) which all get put in the cache. Once I restore them though only the locale is in the clipboard and it appears each call to SetData() overwrites the last. (by the way SetDataObject doesn't seem to be the inverse of GetDataObject so I can't just use that)

任何想法如何存储剪贴板状态并还原它

Any ideas how I can store clipboard state and restore it later?

    [STAThread]
    static void Main(string[] args)
    {
        //Store the old clipboard data
        Dictionary<string, object> clipboardCache = new Dictionary<string, object>();

        IDataObject clipboardData = Clipboard.GetDataObject();

        foreach (string format in clipboardData.GetFormats())
        {
            clipboardCache.Add(format, clipboardData.GetData(format));
        }

        Clipboard.SetText("Hello world!");

        string value = Clipboard.GetText();

        Console.WriteLine(value);

        //Clear the clipboard again and restore old data
        Clipboard.Clear();

        foreach (KeyValuePair<string, object> valuePair in clipboardCache)
        {
            Clipboard.SetData(valuePair.Key, valuePair.Value);
            Thread.Sleep(100);
        }

        Console.ReadLine();
    }


推荐答案

Windows剪贴板只有一个一次放入其中。但该一个对象有多种可用格式(例如RTF,文本,HTML)。我认为您使它变得太复杂了,您的代码应该是这样的:

The windows clipboard only has one object in it at a time. But there are multiple formats available (e.g. RTF, Text, HTML) from that one object. I think you are making it too complicated and your code should be something like this:

//Store the old clipboard data
IDataObject clipboardData = Clipboard.GetDataObject();

Clipboard.SetText("Hello world!");

string value = Clipboard.GetText();
Console.WriteLine(value);

//Clear the clipboard again and restore old data
Clipboard.Clear();
Clipboard.SetDataObject(clipboardData);

Console.ReadLine();

这篇关于剪贴板访问的奇怪性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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