表单显示中的Delphi访问冲突

时间:2018-08-19 18:43:27

标签: forms delphi show access-violation

很抱歉不得不打开新问题,但我在任何地方都找不到答案。

我的应用程序仍在进行中,但是基本上,我在初始化播放器时试图从MainForm调用另一个Form,但是出现访问冲突错误。您能告诉我为什么会这样吗?

我的MainForm代码:

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, ExtCtrls, jpeg, pngimage, getPlayer_u;...

procedure TfrmMain.FormCreate(Sender: TObject);
begin
  Randomize;

  InitGameSetup();
end;...

procedure TfrmMain.InitGameSetup();
begin
  SetWindowProperties();
  InitBackGround();
  InitMainMenu();
  InitGameBoard();
  InitScrabbleTileRack();
  InitPlayers();
//  GameLoop();
end; ...

procedure TfrmMain.InitPlayers();
var
  I : Integer;
  sName, sSurname : string;
begin
  setLength(Players, NUMBER_OF_PLAYERS);
  for I := 1 to High(Players) do
    begin
      GetPlayer(); ---------------- problem is here
      with Players[I] do
        begin
          Name := sName;
          Surname := sSurname;
        end;
    end;
end;...

procedure TfrmMain.GetPlayer();
begin
  frmGetPlayer.Show;
end;

我的frmGetPlayer

unit getPlayer_u;

interface

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

type
  TfrmGetPlayer = class(TForm)
    btnSubmit: TButton;
    edtName: TEdit;
    edtSurname: TEdit;
    procedure FormCreate(Sender: TObject);
    procedure btnSubmitClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    sPlayerName, sPlayerSurname : string;
  end;

var
  frmGetPlayer: TfrmGetPlayer;

implementation

{$R *.dfm}

procedure TfrmGetPlayer.btnSubmitClick(Sender: TObject);
begin
  sPlayerName := edtName.Text;
  sPlayerSurname := edtSurname.Text;

  if not ((Length(sPlayerName) >= 1) and (Length(sPlayerSurname) >= 1)) then
    MessageDlg('Please enter a name and surname.', mtInformation, [mbOK], 0)
  else
    Self.Free;
end;

procedure TfrmGetPlayer.FormCreate(Sender: TObject);
begin
  with Self do
    begin
      Position := poScreenCenter;
      BorderStyle := bsDialog;
    end;
end;

end.

我的dpr:

program main_p;

uses
  Forms,
  main_u in 'main_u.pas' {frmMain},
  getPlayer_u in 'getPlayer_u.pas' {frmGetPlayer};

{$R *.res}

begin
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TfrmMain, frmMain);
  Application.Run;
end.

错误:

Error message: access violation

1 个答案:

答案 0 :(得分:6)

仅MainForm对象在程序启动时自动创建。在其OnCreate事件内部,尚未创建您的Player Form对象,因此frmGetPlayer变量未指向有效的对象。

frmGetPlayer是全局变量,因此最初是nil。错误消息告诉您,您正在访问地址0附近的无效内存,这几乎总是表明已通过nil指针访问类的成员。

因此,只有在创建播放器表单对象并分配frmGetPlayer.Show()指向它之后,才能调用frmGetPlayer。您显示的代码没有执行。