Delphi application with login / logout – how to implement?

Maybe this very simple solution is sufficient:

The project file:

program Project1;

uses
  Forms,
  FMain in 'FMain.pas' {MainForm},
  FLogin in 'FLogin.pas' {LoginForm};

{$R *.res}

var
  MainForm: TMainForm;

begin
  Application.Initialize;
  Application.CreateForm(TMainForm, MainForm);
  Login;
  Application.Run;
end.

The main form:

unit FMain;

interface

uses
  Classes, Controls, Forms, StdCtrls, FLogin;

type
  TMainForm = class(TForm)
    LogoutButton: TButton;
    procedure LogoutButtonClick(Sender: TObject);
  end;

implementation

{$R *.dfm}

procedure TMainForm.LogoutButtonClick(Sender: TObject);
begin
  Login;
end;

end.

And the login form:

unit FLogin;

interface

uses
  Classes, Controls, Forms, StdCtrls;

type
  TLoginForm = class(TForm)
    LoginButton: TButton;
    CancelButton: TButton;
    procedure FormCreate(Sender: TObject);
  end;

procedure Login;

implementation

{$R *.dfm}

procedure Login;
begin
  with TLoginForm.Create(nil) do
  try
    Application.MainForm.Hide;
    if ShowModal = mrOK then
      Application.MainForm.Show
    else
      Application.Terminate;
  finally
    Free;
  end;
end;

procedure TLoginForm.FormCreate(Sender: TObject);
begin
  LoginButton.ModalResult := mrOK;
  CancelButton.ModalResult := mrCancel;
end;

end.

Now, this answer works here, quite well with Delphi 7, but I suspect problems with more recent versions were Application.MainFormOnTaskbar and Application.ShowMainForm are True by default. When so, try to set them to False.

Leave a Comment