Tuesday, July 22, 2008

Sending information between forms/programs

Source: http://www.gamerzplanet.net/forums/misc-programming/194052-delphi-sending-information-between-forms-programs.html

In this little tutorial, we'll be working with a function called SendMessage, which is as telling as it gets. Now, Delphi allows any component to send messages to another component, and the receiving component can choose either to act on it, or not. I use the SendMessage primarily for seperate threads to tell the mainform that it has completed operation.

We'll start out any component/form/procedure/function that will send another component/form/procedure/function a message. For simplicities sake, we'll just send the main form a message. Now, if we want to communicate between forms, we'll have to put the receiving form in the uses clause (under implementation) of the sending form.

Let's try to communicate between forms, ok?

On one form, let's put a button that will send a message to the other form. On the other form, let's put a label to display the message. Let's name the sending form (with the button) SenderForm, although it does not matter what we name it. Let's call the receiving form MainForm.

So, in the OnClick procedure of the SenderForm.Button1 (because that's our button...) we'll do:

Code:
SendMessage(MainForm.Handle, MY_MESSAGE, 0, DWORD(PChar('This is a message for the main form.')));
You might want to save all right now.

Now put the name of the .pas file that uses the MainForm TForm in the uses clause of SenderForm. So if I named the .pas file frmMainForm.pas, i'd put uses frmMainForm;

That's it for the sender form.

Now we'll set up a receiver.

First, we'll define a constant MY_MESSAGE = WM_USER + 4242; directly below the first uses statement.

Then, under TMainForm = class (TForm), past all the GUI items (and along with the other procedures/functions), we'll put

Code:
procedure MessageReceiver(var msg: TMessage); message MY_MESSAGE;
Now, we have to define this procedure. So, under implementation past the uses, consts, and vars, we'll put:

Code:
procedure TMainForm.MessageReceiver(var msg: TMessage);
var
txt: PChar;
begin
txt := PChar(msg.lParam);
msg.Result := 1;
Label1.Caption:= txt;
end;
This way, when the message is sent to the MainForm, it will recieve it, and display it onto the MainForm.

We can also use if statements in our MessageReceiver to determine how the MainForm would act to different messages.



Code:
procedure TMainForm.MessageReceiver(var msg: TMessage);
var
txt: PChar;
i: integer;
begin
txt := PChar(msg.lParam);
msg.Result := 1;
if txt = 'Hide' then MainForm.Hide
else if txt = 'Show' then MainForm.show
else if txt = 'Move' then
begin
for i:= MainForm.Top down to 0 do
MainForm.Top:= i
end;
end;
Now that this example is done, can you do more?

0 Comments: