可能重复:
进程间通信
使用Delphi,我是否有可能构建两个简单的程序,它们可以相互通信和交互,比如说,通过单击第一个程序中的一个按钮,另一个程序会显示一条消息。
有可能吗?
IPC 有许多特性
- 发送窗口消息
- 使用命名管道
- 使用TCP-IP/UDP
- 共享存储器
等等。。。
最简单的方法是将消息发送到FindWindow找到的窗口句柄命名管道和TCP-IP应优先用于广泛的通信。
Microdemo:
第一个项目:
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TTMiniDemoSender = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
TMiniDemoSender: TTMiniDemoSender;
implementation
{$R *.dfm}
Const
C_MyMessage=WM_USER + 1234;
procedure TTMiniDemoSender.Button1Click(Sender: TObject);
var
wnd:HWND;
begin
wnd := FindWindow('TTMiniDemoReceiver',nil);
if wnd<>0 then SendMessage(wnd,C_MyMessage,123,456);
end;
end.
第二个项目:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
Const
C_MyMessage=WM_USER + 1234;
type
TTMiniDemoReceiver = class(TForm)
private
{ Private-Deklarationen }
Procedure MyMessage(var MSG:TMessage); message C_MyMessage;
public
{ Public-Deklarationen }
end;
var
TMiniDemoReceiver: TTMiniDemoReceiver;
implementation
{$R *.dfm}
{ TTMiniDemoReceiver }
procedure TTMiniDemoReceiver.MyMessage(var MSG: TMessage);
begin
Showmessage(IntToStr(MSG.WParam) + '-' + IntToStr(MSG.LParam) );
msg.Result := -1;
end;
end.
要传输更多信息,可以使用WM_CopyData
对于在不同系统上运行的应用程序和其他高级需求,还有消息传递解决方案,如Microsoft消息队列(MSMQ(或基于跨平台消息代理的解决方案,例如开源系统Apache ActiveMQ、HornetQ和RabbitMQ。
有了这些消息传递系统,就很容易实现可靠的对等通信,即使接收器当前没有监听,这种通信也能工作。
有可用的Delphi/FreePascal客户端库,商业的和开源的。