delphi 进程通讯之WM_COPYDATA 发送程序(SendData.exe)


进程通讯之WM_COPYDATA 发送程序(SendData.exe):

unit SendUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TFrmSend = class(TForm)
BtnSend: TButton;
procedure BtnSendClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmSend: TFrmSend;
implementation
{$R *.dfm}
{ TFrmRecv }
procedure TFrmSend.BtnSendClick(Sender: TObject);
var
_vMsg : string;
i, _vLen : Integer;
_vBuf : array of Char;
_vCopyData : TCopyDataStruct;
_vHandle: THandle;
begin
_vMsg := '我是来自另外一个进程的消息!';
_vLen := Length(_vMsg);
SetLength(_vBuf, _vLen);
for i := 0 to _vLen - 1 do
_vBuf[i] := _vMsg[i + 1];
_vCopyData.dwData := 100;
_vCopyData.cbData := _vLen;
_vCopyData.lpData := _vBuf;
_vHandle := FindWindow('TFrmRecv', '接收程序');
if _vHandle <> 0 then
SendMessage(_vHandle, WM_COPYDATA, 0, longint(@_vCopyData));
end;
end.

接收程序(RecvData.exe):

unit RecvUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TFrmRecv = class(TForm)
private
{ Private declarations }
procedure RecvMessage(var aMsg: TWMCOPYDATA); message WM_COPYDATA;
public
{ Public declarations }
end;
var
FrmRecv: TFrmRecv;
implementation
{$R *.dfm}
{ TFrmSend }
procedure TFrmRecv.RecvMessage(var aMsg: TWMCOPYDATA);
var
_vBufLen : Integer;
_vBuf : array of Char;
i : Integer;
_vStr : string;
begin
if aMsg.CopyDataStruct^.dwData = 100 then
begin
_vBufLen := aMsg.CopyDataStruct^.cbData;
System.SetLength(_vBuf, _vBufLen);
Move(aMsg.CopyDataStruct^.lpData^, _vBuf[0], _vBufLen);
_vStr := '';
for i := 0 to _vBufLen - 1 do
_vStr := _vStr + _vBuf[i];
ShowMessage('Len: ' + IntToStr(_vBufLen) + ' ' + _vStr);
end;
end;
end.
联系电话:
020-00000000
联系电话:
020-00000000
联系电话:
020-12345678