System.Messaging (Object Pascal)

From Appmethod Code Examples
Jump to: navigation, search

Description

This example shows how to send and receive messages using the RTL.

It defines a form that contains a text input field and a button. The application behaves as follows:

  • The form defines a method that is called when the default message manager receives a message of UnicodeString type, and this method shows a dialog box with the string from the message.
  • A click on the button sends the string in the input field as a message of UnicodeString type to the default message manager.
Note: This code example is implemented with messages to show how to use them, not because they are the best choice in this case. See When to Use Messages.

To build and test this example:

  1. Create a FireMonkey desktop application.
  2. Add a TEdit and a TButton to your main form.
  3. Change the Text of the button to "Send Message".
  4. Define event handlers with the implementations shown in the Code section below.
    1. Select the form and define an event handler for its OnCreate event.
    2. Select the button and define an event handler for its OnClick event.

System.Messaging.png

Code

unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
  System.Messaging, FMX.Edit;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm1;

implementation

{$R *.fmx}

procedure TForm1.Button1Click(Sender: TObject);
var
  MessageManager: TMessageManager;
  Message: TMessage;
begin
  MessageManager := TMessageManager.DefaultManager;
  Message := TMessage<UnicodeString>.Create(Edit1.Text);
  MessageManager.SendMessage(Sender, Message, True);
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  SubscriptionId: Integer;
  MessageManager: TMessageManager;
begin
  MessageManager := TMessageManager.DefaultManager;
  SubscriptionId := MessageManager.SubscribeToMessage(TMessage<UnicodeString>, procedure(const Sender: TObject; const M: TMessage)
  begin
    ShowMessage((M as TMessage<UnicodeString>).Value);
  end);
end;

end.

Uses

See Also