要在Delphi程序实例之间发送字符串,可以使用以下方法:
在发送方实例中,使用FindWindow
函数找到接收方实例的窗口句柄,然后使用SendMessage
函数发送字符串。
在接收方实例中,使用WM_COPYDATA
消息来接收字符串。
示例代码:
发送方实例:
uses Winapi.Windows, Winapi.Messages;
const
WM_COPYDATA = $004A;
type
PCopyDataStruct = ^TCopyDataStruct;
TCopyDataStruct = record
dwData: ULONG_PTR;
cbData: DWORD;
lpData: PVOID;
end;
var
hWndReceiver: HWND;
s: string;
cds: TCopyDataStruct;
begin
hWndReceiver := FindWindow(nil, 'ReceiverWindowName');
if hWndReceiver <> 0 then
begin
s := 'Hello, this is a string from sender instance.';
cds.dwData := 0;
cds.cbData := Length(s) * SizeOf(Char);
cds.lpData := PChar(s);
SendMessage(hWndReceiver, WM_COPYDATA, 0, LPARAM(@cds));
end;
end;
接收方实例:
uses Winapi.Windows, Winapi.Messages;
const
WM_COPYDATA = $004A;
type
PCopyDataStruct = ^TCopyDataStruct;
TCopyDataStruct = record
dwData: ULONG_PTR;
cbData: DWORD;
lpData: PVOID;
end;
var
s: string;
procedure TForm1.WMCopyData(var Msg: TWMCopyData);
begin
if Msg.CopyDataStruct.dwData = 0 then
begin
SetLength(s, Msg.CopyDataStruct.cbData div SizeOf(Char));
Move(Msg.CopyDataStruct.lpData^, PChar(s)^, Msg.CopyDataStruct.cbData);
ShowMessage(s);
end;
end;
在发送方实例中,创建一个共享内存区域,并将字符串写入该区域。
在接收方实例中,打开该共享内存区域,并从中读取字符串。
示例代码:
发送方实例:
uses Winapi.Windows, System.SysUtils;
const
SharedMemoryName = 'MySharedMemory';
var
hFileMap: THandle;
pView: Pointer;
s: string;
begin
hFileMap := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0, 1024, PChar(SharedMemoryName));
if hFileMap <> 0 then
begin
pView := MapViewOfFile(hFileMap, FILE_MAP_WRITE, 0, 0, 0);
if pView <> nil then
begin
s := 'Hello, this is a string from sender instance.';
Move(PChar(s)^, pView^, Length(s) * SizeOf(Char));
UnmapViewOfFile(pView);
end;
CloseHandle(hFileMap);
end;
end;
接收方实例:
uses Winapi.Windows, System.SysUtils;
const
SharedMemoryName = 'MySharedMemory';
var
hFileMap: THandle;
pView: Pointer;
s: string;
begin
hFileMap := OpenFileMapping(FILE_MAP_READ, False, PChar(SharedMemoryName));
if hFileMap <> 0 then
begin
pView := MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0);
if pView <> nil then
begin
SetLength(s, 1024 div SizeOf(Char));
Move(pView^, PChar(s)^, 1024);
UnmapViewOfFile(pView);
ShowMessage(s);
end;
CloseHandle(hFileMap);
end;
end;
这两种方法都可以实现在不同的Delphi程序实例之间发送字符串。
领取专属 10元无门槛券
手把手带您无忧上云