procedure TForm1.Button1Click(Sender: TObject);
var
hEdit: HWND;
str: string;
begin
str := '准备要添加到记事本的字符串';
WinExec('Notepad.exe', SW_SHOWNORMAL);
hEdit := GetWindow(GetForegroundWindow, GW_CHILD);
SendTextMessage(hEdit, WM_SETTEXT, 0, str);
end;
其中,SendTextMessage是Delphi 2009开始才有的函数,简单好用,说白了就是把消息的LPARAM参数当作字符串指针,传递到另一处,使用起来比较方便,其原型如下:
{$IFNDEF UNICODE}
function SendTextMessage(Handle: HWND; Msg: UINT; WParam: WPARAM; LParam: AnsiString): LRESULT;
begin
Result := SendMessage(Handle, Msg, WParam, Windows.LPARAM(PAnsiChar(LParam)));
end;
{$ENDIF} function SendTextMessage(Handle: HWND; Msg: UINT; WParam: WPARAM; LParam: UnicodeString): LRESULT;
begin
Result := SendMessage(Handle, Msg, WParam, Windows.LPARAM(PWideChar(LParam)));
end; function SendStructMessage(Handle: HWND; Msg: UINT; WParam: WPARAM; const LParam): LRESULT;
begin
Result := SendMessage(Handle, Msg, WParam, Windows.LPARAM(@LParam));
end; function SendGetStructMessage(Handle: HWND; Msg: UINT; WParam: WPARAM;
var LParam; Unused: Boolean = False): LRESULT;
begin
Result := SendMessage(Handle, Msg, WParam, Windows.LPARAM(@LParam));
end; function SendGetIntMessage(Handle: HWND; Msg: UINT; var WParam: Integer;
var LParam: Integer): LRESULT;
begin
Result := SendMessage(Handle, Msg, Windows.WPARAM(@WParam), Windows.LPARAM(@LParam));
end;
需要注意的是,这种用法不仅仅是指发送WM_SETTEXT消息,而是可以是任何消息。一般由程序员手动写代码发送,而不是由Windows产生的消息,因为这里LPARAM的含义已经提前被占用了。
参考:http://www.cnblogs.com/del/archive/2009/11/12/1601703.html
-----------------------------------------------------------------------------------
{用 API 实现的获取文本容器中选择的文本的函数}
function GetEditSeleteText(h: HWND): string;
var
len,sx,ex: Integer; {文本总长度, 选择的开始位置, 选择的结束位置}
buf: PChar; {所有文本}
begin
{获取文本总长度}
len := SendMessage(h, WM_GETTEXTLENGTH, 0, 0) + 1;
{为接受所有文本的缓冲区分配内存}
buf := GlobalAllocPtr(0, len); {这里没有使用 GetMem, 因为需要全局的, 不然无法面对其他程序}
{获取所有文本}
SendMessage(h, WM_GETTEXT, len, Longint(buf));
{获取选择的开始位置和结束位置}
SendMessage(h, EM_GETSEL, Longint(@sx), Longint(@ex));
{截取选择的文本}
Result := Copy(buf, sx+1, ex-sx);
{释放内存}
GlobalFreePtr(buf);
end; {测试 TEdit, 同时与 VCL 的获取方法对比}
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(GetEditSeleteText(Edit1.Handle) + ' - ' + Edit1.SelText);
end; {测试 TMemo, 同时与 VCL 的获取方法对比}
procedure TForm1.Button2Click(Sender: TObject);
begin
ShowMessage(GetEditSeleteText(Memo1.Handle) + ' - ' + Memo1.SelText);
end; {测试 TRichEdit, 同时与 VCL 的获取方法对比}
procedure TForm1.Button3Click(Sender: TObject);
begin
ShowMessage(GetEditSeleteText(RichEdit1.Handle) + ' - ' + RichEdit1.SelText);
end;
参考:http://www.cnblogs.com/del/archive/2008/06/19/1225080.html