忘記是抄誰的了,這裡改進了一下。還原後沒有clear 並再一次備份。
因為還原一次後,如果再還原,會控制程式碼無效的。
unit clipbak; interface uses SysUtils, Classes, Clipbrd, Windows, Contnrs, Dialogs; type TClipData = class Format: WORD; Data: THANDLE; end; TClipBackuper = class private ClipList: TList; public constructor Create; destructor Destroy; override; procedure BackupClip(); function RestoreClip:Boolean; end; implementation constructor TClipBackuper.Create; begin Cliplist := TObjectList.Create; end; destructor TClipBackuper.Destroy; begin ClipList.Free; end; procedure TClipBackuper.BackupClip; var i: Integer; Data: THANDLE; pcd: TClipData; DataMem: Pointer; FileName : array [0..255] of Char; FileStr:string; begin ClipList.Clear; Clipboard.Open; try for i := 0 to Clipboard.FormatCount - 1 do begin pcd := TClipData.Create; pcd.Format := Clipboard.Formats[i]; Data := THANDLE(Clipboard.GetAsHandle( pcd.Format)); // GetClipboardFormatName(pcd.Format, FileName, 255); // FileStr := string(FileName); // OutputDebugString(pchar(FileStr)); if (Data = 0) then begin pcd.free; continue; end; //分配記憶體 pcd.Data := GlobalAlloc(GMEM_MOVEABLE or GMEM_DDESHARE, GlobalSize(Data)); //鎖定記憶體 DataMem := GlobalLock(pcd.Data); //有分配成功的話,複製當前剪下板的記憶體資料 if (DataMem <> nil) then begin CopyMemory(DataMem, GlobalLock(Data), GlobalSize(Data)); //解鎖 GlobalUnlock(THANDLE(pcd.Data)); GlobalUnlock(THANDLE(Data)); end; ClipList.Add(pcd); end; finally Clipboard.Close; end; end; //還原回去後,要再一次backup 不然再RestoreClip 不會再一次還原不會成功 function TClipBackuper.RestoreClip:Boolean; var pcd: TClipData; i: Integer; begin Clipboard.Open(); try Clipboard.Clear(); for i := 0 to ClipList.Count - 1 do begin pcd := TClipData(ClipList[i]); if SetClipboardData(pcd.Format, pcd.Data) <= 0 then begin Result := False; Exit; end; end; finally Clipboard().Close(); end; BackupClip; //再備份一次 Result := True; end; end.