前面曾今展示过利用WM_COPYDATA交换数据的方法。 这次将演示利用内存映射技术实现数据传递的方法: a.发送端: 代码如下: unit sendunit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TForm1 = class(TForm) Edit1: TEdit; Label1: TLabel; BitBtn1: TBitBtn; procedure BitBtn1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public procedure SendData; { Public declarations } end; var Form1: TForm1; MapFilehWnd: THandle; MapFilePointer: Pointer; implementation {$R *.dfm} procedure TForm1.SendData; //发送消息和数据过程 begin MapFilehWnd := CreateFileMapping ($FFFFFFFF,nil,page_ReadWrite, 0,10000,'MapFileDemo'); if MapFilehWnd <> 0 then begin MapFilePointer := MapViewOfFile (MapFilehWnd ,FILE_MAP_ALL_ACCESS,0, 0, 0); StrCopy(PChar(MapFilePointer),PChar (Edit1.Text)); end; end; procedure TForm1.BitBtn1Click(Sender: TObject); begin if Edit1.Text<>'' then SendData; end; procedure TForm1.FormCreate(Sender: TObject); begin MapFilehWnd:=0; MapFilePointer:=Nil; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin if MapFilePointer<>Nil then begin UnmapViewOfFile(MapFilePointer); CloseHandle(MapFilehWnd); end; end; end. b.接收端: 如下图所示建立工程: 代码如下: unit Receiveunit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type TForm1 = class(TForm) Edit1: TEdit; Label1: TLabel; Timer1: TTimer; procedure Timer1Timer(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Timer1Timer(Sender: TObject); var MapPointer:Pointer; begin if (OpenFileMapping(FILE_MAP_ALL_ACCESS,False,'MapFileDemo')<>0) then begin MapPointer:=MapViewOfFile(OpenFileMapping(FILE_MAP_ALL_ACCESS,False,'MapFileDemo'),FILE_MAP_ALL_ACCESS,0,0,0); Edit1.Text := PChar (MapPointer);//从共享内存读出内容 end; end; end.