问题描述
- c# Clipboard操作。如何保存剪贴板内容,在操作完成后恢复内容
-
看过别人的方法,将各种数据分类读取到数据,占用剪贴板完成后再分类保存。但这种方法存在问题。因为C#的剪贴板读取和保存数据类型是有限的,如果对于一些用户自定义书记的剪贴板或者其他程序的自定义数据。操作后是不能如实恢复剪贴板的。别人的例子程序。
object xx = null;
string ctype = "";
try
{
if (Clipboard.ContainsText())
{
ctype = "Text";
xx = Clipboard.GetText();
}
else if (Clipboard.ContainsFileDropList())
{
ctype = "FileDrop";
xx = Clipboard.GetFileDropList();
}
。。。。。。。。。。。。。。。想要达到的效果。
data=clipboard.get....
占用剪贴板。。。。。
clipboard.set.....(data);
前后data数据不会改变。请问该如何实现
解决方案
在c#中试了一下,有些问题,建议你参考这个c++builder写的代码
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include <clipbrd.hpp>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
TList* ClipList = new TList;
struct ClipData
{
WORD Format;
HANDLE Data;
ClipData() { Format = 0; Data = NULL; }
~ClipData() { if (Data) GlobalFree(Data); }
};
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormDestroy(TObject *Sender)
{
for(int n=0; n<ClipList->Count; n++) {
delete (ClipData*)ClipList->Items[n];
}
ClipList->Clear(); delete ClipList;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::SaveClipBtnClick(TObject *Sender)
{
HANDLE Data;
ClipData* pcd;
for(int n=0; n<ClipList->Count; n++) {
delete (ClipData*)ClipList->Items[n];
}
ClipList->Clear(); Clipboard()->Open();
for(int n=0; n<Clipboard()->FormatCount;
n++) {
if ((pcd=new ClipData) == NULL)
break;
pcd->Format = Clipboard()->Formats[n];
Data = (HANDLE)Clipboard()->GetAsHandle(
pcd->Format);
if (Data == NULL) {
delete pcd; continue;
}
pcd->Data = GlobalAlloc(GMEM_MOVEABLE|
GMEM_DDESHARE, GlobalSize(Data));
void* DataMem = GlobalLock(pcd->Data);
if (DataMem != NULL) {
memcpy(DataMem, GlobalLock(Data),
GlobalSize(Data));
GlobalUnlock((HANDLE)pcd->Data);
GlobalUnlock((HANDLE)Data);
}
ClipList->Add(pcd); continue;
}
Clipboard()->Close();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::RestoreClipBtnClick(TObject *Sender)
{
HANDLE Data;
ClipData* pcd;
Clipboard()->Open();
Clipboard()->Clear();
for(int n=0; n<ClipList->Count; n++) {
ClipData* pcd = (ClipData*)ClipList
->Items[n];
SetClipboardData(pcd->Format, pcd->
Data);
pcd->Data = NULL; delete pcd;
}
ClipList->Clear(); Clipboard()->Close();
}
解决方案二:
Clipboard.GetDataObject
Clipboard.SetDataObject
解决方案三:
IDataObject iData = Clipboard.GetDataObject();
//对剪切板进行处理
Clipboard.SetDataObject(iData)