1.共享内存
//创建共享内存 hMapFile := CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file nil, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) 256, // maximum object size (low-order DWORD) PChar(globalCloseName)); // name of mapping object if hMapFile <> 0 then begin pshare := MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, 256); if PShare = nil then begin closehandle(hMapFile); hMapFile := 0; end; end;
//释放共享内存 CloseHandle(hMapFile); UnmapViewOfFile(pshare);
//引用共享内存 hMapFile := OpenFileMapping( FILE_MAP_ALL_ACCESS, // read/write access FALSE, // do not inherit the name PChar(globalCloseName)); // name of mapping object if hMapFile <> 0 then begin PShare := MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, 255); if PShare = nil then begin CloseHandle(hMapFile); hMapFile := 0; end; end;
2.消息
//发送消息 procedure SendProgramMsg(DesForm: THandle; wIdent,lp: Word;sSendMsg:string); var SendData : TCopyDataStruct; nParam : Integer; begin nParam := MakeLong(lp, wIdent); SendData.cbData := Length(AnsiString(sSendMsg)) + 1; GetMem(SendData.lpData, SendData.cbData); (PAnsiChar(SendData.lpData) + SendData.cbData)^ := #0; Move(PAnsiChar(AnsiString(sSendMsg))^, PAnsiChar(AnsiString(SendData.lpData))^, Length(AnsiString(sSendMsg)) + 1); SendMessage(DesForm, WM_COPYDATA, nParam, Cardinal(@SendData)); FreeMem(SendData.lpData); end;
//接收消息 procedure TfMain.MyMessage(var MsgData: TWmCopyData); var sRecv: AnsiString; sData: string; wIdent, wRecog: Word; begin wIdent := HiWord(MsgData.From); wRecog := LoWord(MsgData.From); sRecv := AnsiString(PAnsiChar(MsgData.CopyDataStruct^.lpData)); sData:= string(sRecv); case wIdent of end; end;