1.RegisterWindowMessage() //参数类型:pchar;返回值:LongInt;
2.FindWindow(
lpClassName, {窗口的类名}
lpWindowName: PChar {窗口的标题}
): HWND; {返回窗口的句柄; 失败返回 0}
3.Wndproc()//每个窗口会有一个称为窗口过程的回调函数(WndProc),
它带有四个参数,分别为:窗口句柄(Window Handle),消息ID(Message ID),和两个消息参数(wParam, lParam)
4.PostMessage() //该函数将一个消息放入(寄送)到与指定窗口创建的线程相联系消息队列里,不等待线程处理消息就返回,是异步消息模式。消息队列里的消息通过调用GetMessage和PeekMessage取得。取得后交由WndProc进行处理。
好了,需要的知识都在这里了,现在开始我们的应用程序之间通信。
首先在两个应用程序的主窗体的创建过程注册消息,消息编号一定要不小于WM_USer,然后在程序1中得到程序2的主窗体句柄,并通过PostMessage向其发送消息;
接下来在程序2的主窗体创建过程注册和程序1相同编号的消息,然后重载程序2的Wndproc过程。废话就不多说了,直接贴代码:
////////////////////////////////////////////////////////////////////程序1//////////////////////////////////////////////////////////////////////////
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TForm1 = class(TForm) Button2: TButton; Button3: TButton; BitBtn1: TBitBtn; procedure Button2Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure BitBtn1Click(Sender: TObject); private { Private declarations } I: Integer; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} { TForm1 } procedure TForm1.FormShow(Sender: TObject); begin I:= RegisterWindowMessage('MyMessage'); end; procedure TForm1.BitBtn1Click(Sender: TObject); var h1: HWND; begin h1:= FindWindow(nil,'Form2'); PostMessage(h1,I,0,1); end;
////////////////////////////////////////////////////////////////////程序2/////////////////////////////////////////////////////////////////////
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AppEvnts, Buttons,QExtCtrls, ExtCtrls; const My_MousL = WM_USER+100; type TForm2 = class(TForm) Button1: TButton; ApplicationEvents1: TApplicationEvents; BitBtn1: TBitBtn; BtnCreatePanel: TBitBtn; BitBtn2: TBitBtn; BitBtn3: TBitBtn; Panel1: TPanel; Button2: TButton; procedure FormShow(Sender: TObject); private { Private declarations } J: Integer; public { Public declarations } procedure WndProc(var Message: TMessage); override; end; var Form2: TForm2; implementation {$R *.dfm} procedure TForm1.FormShow(Sender: TObject); begin J:= RegisterWindowMessage('MyMessage'); end; procedure TForm1.WndProc(var Message: TMessage); begin if Message.Msg = J then showmessage('得到消息') else inherited; end;
至此,应用程序间通信就完成了,这里需要注意:FindWindow一定要找到你想要得到消息的应用程序,也就是说如果用FindWindow(nil,'Form2'),你一定得保证窗体的caption:= Form2的程序是唯一的。