Author: Igor Siticov
I want to perform communication between two my applications or between two
instances of my application.
Answer:
You can perform communication between your application using Windows messages
exchange mechanism. We can use HWND_BROADCAST value for first parameter for
SendMessage function for suppressing finding of forms' in other applications
HANDLE.
For using HWND_BROADCAST we should register our messages in Windows.
For performing this you could make the following:
(In example below we will inform about our form's top position)
1. Define type of your message structure, it could be something like this:
1 type2 TWMMYMessage = record3 Msg: Cardinal; // ( first is the message ID )4 Handle: HWND; // ( this is the wParam, Handle of sender)5 Info: LongInt; // ( this is lParam, pointer to our data)6 Result: LongInt;
7 end;
2. Override your form's DefaultHandler method and add method for handling your
message, like this
8 TForm1 = class(TForm)
9 {... }10 public11 { Public declarations }12 {... }13 procedure DefaultHandler(varmessage); override;
14 procedure WMMYMessage(var Msg: TWMMYMessage);
15 {... }16 end;
3. Declare message variable:
17 var18 WM_OURMESSAGE: DWORD;
4. Insert realisation of DefaultHandler and our message handler methods:
19 20 procedure TForm1.DefaultHandler(varmessage);
21 var22 ee: TWMMYMessage;
23 begin24 with TMessage(message) do25 begin26 if (Msg = WM_OURMESSAGE) then27 begin28 ee.Msg := Msg;
29 ee.Handle := wParam;
30 ee.Info := lParam;
31 // Checking if this message is not from us32 if ee.Handle <> Handle then33 WMMYMessage(ee);
34 end35 else36 inherited DefaultHandler(message);
37 end;
38 end;
39 40 procedure TForm1.WMMYMessage(var Msg: TWMMYMessage);
41 begin42 Label1.Caption := Format('Our another form handle :%d', [Msg.Handle]);
43 Label2.Caption := Format('Our another form top :%d', [Msg.Info]);
44 end;
5. Add registration of your message that you could handle the HWND_BROADCAST
messages:
initialization
WM_OURMESSAGE := RegisterWindowMessage('Our broadcast message');
6. Add the message sending somewhere:
procedure TForm1.Button1Click(Sender: TObject);
begin
SendMessage(HWND_BROADCAST, WM_OURMESSAGE, Handle, Top);
end;
7. Compile and run two copies of your application and test it functionality.