Delegates and Events

Delegate is a special type that is used to describe custom events. Delegates determine the signature of the methods, which can be used as custom event handlers.

Example

Executing the example requires the following:

  1. Create an assembly and two forms named StyleForm and MainForm in this assembly.

  2. The forms can have the following code:
    //Form StyleForm
    Delegate ChangeStyle(FontBold: Boolean; FontName: String; FontSize: Integer);
    Class StyleForm: Form
        Label1: Label;
        Friend Event OnChangeStyle: ChangeStyle;
        
        CheckBox1: CheckBox;
        ComboBox1: ComboBox;
        IntegerEdit1: IntegerEdit;
        Label2: Label;
        
        Sub ChangeStyle(Sender: Object; Args: IEventArgs);
        Begin
            If OnChangeStyle <> Null Then
                OnChangeStyle(CheckBox1.Checked, ComboBox1.Items.Item(ComboBox1.ItemIndex), IntegerEdit1.Value);
            End If;
        End Sub ChangeStyle;
    End Class StyleForm;


    //Form MainForm
    Class MainForm: Form
        Label1: Label;
        Label2: Label;
        ControlBar1: ControlBar;
        GroupBox1: GroupBox;
        EditBox1: EditBox;
        DateTimePicker1: DateTimePicker;
        Button1: Button;
        UiTabSheet1: UiTabSheet;
        TabSheetBox1: TabSheetBox;
        
        //The procedure for handling the OnChangeStyle event
        Sub ChangeStyle1(FontBold: Boolean; FontName: String; FontSize: Integer);
        Var
            f: IControlFont;
            f1: ITabFont;
        Begin
            f := Self.Font;
            f.Bold := FontBold;
            f.Name := FontName;
            f.Size := FontSize;
            f1 := UiTabSheet1.TabSheet.Table.Style.Font;
            If FontBold Then
                f1.Bold := TriState.OnOption;
            Else
                f1.Bold := TriState.OffOption;
            End If;
            f1.Name := FontName;
            f1.Size := FontSize;
        End Sub ChangeStyle1;
        
        Sub MainFormOnCreate(Sender: Object; Args: IEventArgs);
        Begin
            (ControlBar1.Form As StyleForm).OnChangeStyle := ChangeStyle1;
        End Sub MainFormOnCreate;
    End Class MainForm;

When the MainForm form is started during the initialization of the ControlBar component the StyleForm form is created. The OnChangeStyle custom event is created for this form. This event is used to change component formatting. This event is available in all assembly forms. The signature of methods that are used to handle this event is described by the ChangeStyle delegate.

Executing the OnCreate procedure of the MainForm form subscribes this form to the OnChangeStyle event of the StyleForm form. To handle this event, the ChangeStyle1 procedure is used in this form.

See also:

Classes and Objects