如何保存Windows剪贴板数据并更改它并使用它然后还原它? [英] How to save windows clipboard data and change it and use it and then restore it?

查看:139
本文介绍了如何保存Windows剪贴板数据并更改它并使用它然后还原它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows窗体应用程序中:



我有一个翻译程序,需要在全局按F1时获取所选文本,它会将Ctrl + C发送到活动窗口在Windows中然后使用文本并进行翻译,现在我希望它在我的程序发送Ctrl + C之前恢复剪贴板中的内容。



我是什么尝试过:



In Windows forms applications:

I have a translation program that needs to get the selected text when F1 is pressed globally, it sends Ctrl+C to active window in Windows and then uses the text and translates it, now I want it to restore what was in clipboard before my program sent Ctrl+C.

What I have tried:

//Backup
var lBackup = new Dictionary<string, object>();
var lDataObject = Clipboard.GetDataObject();
var lFormats = lDataObject.GetFormats(false);
foreach(var lFormat in lFormats)
{
  lBackup.Add(lFormat, lDataObject.GetData(lFormat, false));
}

//Set test data
Clipboard.SetText("asd");

//Would be interesting to check the contents of lDataObject here

//Restore data
foreach(var lFormat in lFormats)
{
  lDataObject.SetData(lBackup[lFormat]);
}
//This might be unnecessary
Clipboard.SetDataObject(lDataObject);

推荐答案

请参阅剪贴板类(System.Windows.Forms) [ ^ ]


Theres是这个,但他们在评论中说它有错误。



< a href =https://www.codeproject.com/Articles/15333/Clipboard-backup-in-C> C#中的剪贴板备份 [ ^ ]



你有吗?一个更好的代码?
Theres's this but they say in comments that it has errors.

Clipboard backup in C#[^]

Do you have a better code?


这是你需要做的基本概述。

Here is a basic outline of what you need to do.
IDataObject iData = Clipboard.GetDataObject(); // get a link to the ClipBoard data
string strSave = (string)iData.GetData(DataFormats.Text); // get the object's data

// do your copying & translating

Clipboard.SetText(strSave, TextDataFormat.UnicodeText); // restore original cotents



这是只是一个用于保存和恢复某些Unicode文本的简单模板。您需要添加代码以满足所有不同格式的数据,如剪贴板类的文档所示 - 请参阅上面给出的链接。


This is just a simple template for saving and restoring some Unicode text. You need to add code to cater for all the different formats of data, as shown in the documentation for the Clipboard class - see the link I gave you above.


这篇关于如何保存Windows剪贴板数据并更改它并使用它然后还原它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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