Pass parameter when creating a new form in delphi SDI

Eduard picture Eduard · Dec 25, 2012 · Viewed 8.6k times · Source

Ok, I'm sorry if this is a little bit confusing but I don't know how to explain it better. I have a chat form that is shown after the user has previously authenticated in TLoginForm.

User logged in then show the chatForm:

with TChatForm.Create(Application) do
begin
    Show;
end;

My problem is , how can I pass the username to the chatForm so I can use it as nickname in the chat, considering the fact that the form automatically connects to server OnShow, so I'll be needing the username sent already.

I'm new to delphi so if there's any mistake in my code, kindly excuse me.

Answer

David Heffernan picture David Heffernan · Dec 25, 2012

If the username should be fixed during the entire lifetime of the object then it should be passed in to the constructor. The benefit is that it's not possible to misuse the class and forget to assign the username.

Declare a constructor that receives the extra information in parameters:

type
  TMyForm = class(TForm)
  private
    FUserName: string;
  public
    constructor Create(AOwner: TComponent; 
        const UserName: string);
  end;

constructor TMyForm.Create(AOwner: TComponent; 
        const UserName: string);
begin
  inherited Create(AOwner);
  FUserName := UserName;
end;

Create the form like this:

MyForm := TMyForm.Create(Application, UserName);