program Project1;
{$APPTYPE CONSOLE}
uses
Windows, SysUtils;
function GetTitle(Wnd: HWND): String;
var
lpch: String;
len: DWORD;
begin
len := GetWindowTextLength(Wnd);
SetLength(lpch, len);
GetWindowText(Wnd, PChar(lpch), Length(lpch) + 1);
Result := lpch;
end;
function GetClipboardText(Wnd: HWND; var Str: string): Boolean;
var
hData: HGlobal;
begin
Result:=True;
if OpenClipboard(Wnd) then begin
try
hData:=GetClipboardData(CF_TEXT);
if hData<>0 then begin
try
SetString(Str, PChar(GlobalLock(hData)), GlobalSize(hData));
finally
GlobalUnlock(hData);
end;
end else Result:=False;
Str:=PChar(@Str[1]);
finally
CloseClipboard;
end;
end else Result:=False;
end;
function SetClipboardText(Wnd: HWND; Value: string): Boolean;
var
hData: HGlobal;
pData: pointer;
Len: integer;
begin
Result:=True;
if OpenClipboard(Wnd) then begin
try
Len:=Length(Value)+1;
hData:=GlobalAlloc(GMEM_MOVEABLE or GMEM_DDESHARE, Len);
try
pData:=GlobalLock(hData);
try
Move(PChar(Value)^, pData^, Len);
EmptyClipboard;
SetClipboardData(CF_Text, hData);
finally
GlobalUnlock(hData);
end;
except
GlobalFree(hData);
raise
end;
finally
CloseClipboard;
end;
end else Result:=False;
end;
var
s, ss: string;
wnd: HWND;
begin
wnd := GetForegroundWindow;
ss := GetTitle(wnd);
WriteLn('Window Caption: ', ss);
s := '';
if SetClipboardText(wnd, ss) then
begin
WriteLn('Copy to clipboard success.');
if GetClipboardText(wnd, s) then
begin
WriteLn('Text from clipboard: ', s);
end
else
WriteLn('Unabled to get text from clipboard.');
end
else
WriteLn('Copy to clipboard failed.');
ReadLn;
end.