在表单处于活动状态之前终止表单的创建

时间:2013-07-23 17:28:00

标签: delphi

我希望用户在他/她能够查看表单之前登录...

它似乎不起作用。

有什么想法吗?

sLoginID := InputBox('Ink Spots','Please enter login ID:','');
  sLoginPassword := InputBox('Ink Spots','Please enter password for ' + sLoginID,'');
  if sLoginID <> 'user'
    then
    begin
      ShowMessage('You shall not pass!');
      Self.Close;
    end
    else
    begin
      sLoginPassword := InputBox('Ink Spots','Please enter password for ' + sLoginID,'');
      if sLoginPassword <> 'pass'
        then
        begin
          ShowMessage('You shall not pass!');
          Self.Close;
        end;
    end

2 个答案:

答案 0 :(得分:10)

如果不打算创建表单,那么它应该从其构造函数中抛出异常。这是避免创建对象的定义方式。请注意,OnShowOnCreate不是构造函数;您需要覆盖Create

在您的情况下,您试图在错误的地方解决问题。避免创建您不想要的表单的更好方法是永远不要创建它。而不是创建表单,然后检查是否允许它,检查是否允许它首先,然后然后显示它。

您可以将该操作包装到函数中,以便为调用者提供便利。例如:

class function TRijnhardtForm.ConditionallyCreate: TRijnhardtForm;
var
  LoginID, LoginPassword: string;
begin
  Result := nil;
  LoginID := InputBox(Application.Title, 'Please enter login ID:','');
  LoginPassword := InputBox(Application.Title, 'Please enter password for ' + LoginID, '');
  if LoginID <> 'user' then begin
    ShowMessage('You shall not pass!');
    Exit;
  end;
  LoginPassword := InputBox(Application.Title, 'Please enter password for ' + LoginID, '');
  if LoginPassword <> 'pass' then begin
    ShowMessage('You shall not pass!');
    Exit;
  end;
  Result := TRijnhardtForm.Create(Application);
end;

然后,您可以使用该方法创建表单,但前提是用户正确且密码输入两次。

RijnhardtForm := TRijnhardtForm.ConditionallyCreate;

答案 1 :(得分:0)

在您的项目来源中......

program Project49;

uses
  Forms,
  Unit56 in 'Unit56.pas' {Form56};

{$R *.res}

begin
  Application.Initialize;
  Application.CreateForm(TForm56, Form56);
  Login;
//Most importantly...comment out Application.Run
//  Application.Run;
end.

然后将您的登录信息更改为程序

unit Unit56;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TForm56 = class(TForm)
  private
    { Private declarations }
  public
    { Public declarations }

  end;
  procedure Login;
var
  Form56: TForm56;

implementation

{$R *.dfm}
procedure Login;
var
 a_Login: boolean;
 sLoginId, sLoginPassword: string;
begin
 a_Login:= False;
 sLoginID := InputBox('Ink Spots','Please enter login ID:','');
//     sLoginPassword := InputBox('Ink Spots','Please enter password for ' + sLoginID,'');
 if sLoginID <> 'user'
 then
 begin
  ShowMessage('You shall not pass!');
  //Self.Close;
 end
 else
 begin
  sLoginPassword := InputBox('Ink Spots','Please enter password for ' + sLoginID,'');
  if sLoginPassword <> 'pass'
    then
    begin
      ShowMessage('You shall not pass!');
      //Self.Close;
    end else
      a_Login := True;
 end;
 if a_Login then
   Application.Run;
end;



end.