Search code examples
delphicallbackprocedure

How to pass back values from non modal form to main form without closing the non modal one


My Delphi application has two forms: the main one with a grid and a button Modify. I select a row in the grid then click Modify. This has effect to open a non modal windows where I can modify some values extracted from the selected row of the grid. If I click OK, I want to pass modifications back to the main form (and to the grid) but without closing the non modal form. That's why I don't want to use a modal one. How can I do that? I guess I need callback procedure but I can not figure out how to proceed


Solution

  • I don't like to make helper forms (your "non modal form") aware of the main form as this makes them less reusable. On the other hand, main form knowing details about the helper form is OK. So I'd do it slightly differently than in David's answer.

    Declare method type for the callback and give the form an property of that type:

    type
      TDataChangedEvent = procedure(const aText: string) of object;
    
      THelperForm = class(TForm)
      public
        OnDataChanged: TDataChangedEvent;
      ...
      end;
    

    On the main form, have an method of that type and when when you click Modify assign it to the helper form's property:

    procedure TMainForm.OnDataCallback(const aText: string);
    begin
      ShowMessage(aText);
    end;
    
    procedure TMainForm.OnModifyClick(Sender: TObject);
    var HelperWnd: THelperWnd;
    begin
      HelperWnd := THelperWnd.Create(Self);
      HelperWnd.OnDataChanged := Self.OnDataCallback;
      HelperWnd.Show;
    end;
    

    And in the helper form's OK button's OnClick handler you call the method assigned to the property:

    procedure THelperForm.OnbtnOKClick(Sender: TObject);
    begin
      if Assigned(OnDataChanged) then OnDataChanged(Edit1.Text)
    end;