Search code examples
windowsformsdelphisend

Delphi sending value between two windows - createparams override


Hello I have main form and two another forms. Both have this code on createparams

procedure TfrForm2.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  with Params do
  begin
    ExStyle := ExStyle or WS_EX_APPWINDOW;
  end;
end;

and both (TfrForm2 and TfrForm3) are opened from main form by using code :

with TfrForm2.Create(Application) do
  try
    Show;
  finally
  end;

So i can have 3 buttons on taskabr (main,form2,form3). But how can i send data (for example integer value) between form2 and form3 or bring to front form2 from form 3 (by clicking button etc on form 3) ? ?


Solution

  • As David Heffernan already said the easiest way is through the usage of form reference.

    If each form is declared in its seperate unit you can add that unit into uses section which will give you access to that form reference.

    Do note that in order to avoid circular referencing you should add the other form unit into uses section which is part of the implementation section (the one in the middle of the unit) and not the one that is part of interface section (the on top of the unit).

    Doing so adds you access to objects, methods, variables and constants delcared in that specific unit but it does not allow you to derive any subclass of existing objects there unless you are doing so with declaration of local types (declaring object type inside the scope of an existing method).

    unit UMainForm;
    
    interface
    
    uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
    
    type
      TMainForm = class(TForm)
      private
        { Private declarations }
      public
        { Public declarations }
      end;
    
    var
      MainForm: TMainForm;
    
    implementaion
    //Add another form unit here to avoid problems with circular referencing
    uses UMySecondForm;
    

    By default delphi doesn't add anything into implementaion uses section so there is no uses clause there. So you should add it yourself.

    WARNING! When accessing another form through its reference that is delcared in another unit pay special attention to first check if the form reference does indeed reference the proper form object (make sure the form has already been created and not yet destroyed) othervise you will end up with lots of Access Violation errors.