Jump to content
Fudley

TForm to TForm communication

Recommended Posts

delphi 12, fmx, android

 

What is a simple technique for sending communications from one TForm to another TForm?

(other than filling a hidden label or clicking a hidden button on the target form maybe?)

 

Share this post


Link to post

That looks promising Rollo62. Say I want FormB to send an integer message to FormA  i.e. 999 and have FormB receive and perform the instruction represented by 999. i.e. 

case integer-message of
1:
2:
3:
99: perform task 99
end

How would I set up it up. I am still  confused by the TMessageManager subscribe and unsubsribe, and how to send message from one to the other.

Share this post


Link to post

First, declare the message type in a common unit:

type
  TIntegerMessage = class(TMessage<Integer>);

Second, declare a TMessageListenerMethod in FormA handling that message type:

type
  TFormA = class(TForm)
    ...
  private
    procedure MyMessageHandler(const Sender: TObject; const M: TMessage);
  ...

procedure TFormA.MyMessageHandler(const Sender: TObject; const M: TMessage);
begin
  var msg := M as TIntegerMessage;
  // do something with the Integer you get from msg.Value
end;

Third, subscribe/unsubscribe to this message type in TFormA.FormCreate/FormDestroy:

procedure TFormA.FormCreate(Sender: TObject);
begin
  TMessageManager.DefaultManager.SubscribeToMessage(TIntegerMessage, MyMessageHandler);
end;

procedure TFormA.FormDestroy(Sender: TObject);
begin
  TMessageManager.DefaultManager.Unsubscribe(TIntegerMessage, MyMessageHandler);
end;

Finally, send the message in FormB:

begin
  ...
  TMessageManager.DefaultManager.SendMessage(Self, TIntegerMessage.Create(42));
  ...
end;

Note: Only the common unit with the type declaration has to be used by both form units. None of them needs to use the other form unit.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×