設置剪貼板數據:
先用GlobalAlloc在堆中分配空間,返回的Hmem句柄將作為SetClipboardData的第二個參數。
然后用GlobalLock把Hmem轉為指針,再用delphi的strCopy把字符串寫入。
取剪貼板數據:
獲取剪貼板里的數據時,是不知道當前剪貼板里是否有數據的,也不知道剪貼板里的數據格式是什么。那么下面就來解決這兩個問題,先使用函數IsClipboardFormatAvailable來獲取剪貼板里的格式是否可以處理,接着使用函數OpenClipboard打開剪貼板,然后使用函數GetClipboardData來獲取剪貼板數據
源代碼如下:
-----------------------------------------------------------
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
*******
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
s1:string;
hmem:HGLOBAL;
pstr:PChar;
begin
s1:='豬悟能在test剪貼板';
hmem:=GlobalAlloc(GMEM_MOVEABLE or GMEM_DDESHARE,Length(s1)+4);
pstr:=GlobalLock(hmem);
StrCopy(pstr,PChar(s1));
if OpenClipboard(0)then
begin
SetClipboardData(CF_TEXT,hmem);
CloseClipboard;
GlobalUnlock(hmem);
GlobalFree(hmem);
ShowMessage('字符串已經復制到剪貼板');
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
hmem:THandle;
pstr:PChar;
begin
//檢查剪貼板類容類型
if IsClipboardFormatAvailable(CF_TEXT) then
begin
OpenClipboard(0);
hmem:=GetClipboardData(CF_TEXT);
pstr:=GlobalLock(hmem);
Memo1.Text:=pstr;
GlobalUnlock(hmem);
CloseClipboard;
end;
end;
end.
用#9查找tab符號:
ipos := pos(#9,sTmp)