It's my first post, so hello to everyone.
I'm completely new to Lazarus (literally started today).
I created a project and can't make it do two simple things:
- Start my server automatically.
- Give access to the procedure Log() to my second unit.
If I put the code in a button and press it after the form is shown, everything works fine. But I want it to start automatically with my program without the need to press a button.
The project has two units: Unit1 and Commands.
The first unit has a form, the second had code only.
Here is a part of both of them:
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls,
IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, IdContext,
Commands, IdGlobal;
type
{ TForm1 }
TForm1 = class(TForm)
btnStart: TButton;
btnStop: TButton;
MemoLog: TMemo;
TcpServer: TIdTCPServer;
procedure btnStartClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure TcpServerConnect(AContext: TIdContext);
procedure TcpServerDisconnect(AContext: TIdContext);
procedure TcpServerExecute(AContext: TIdContext);
private
procedure Log(const S: string);
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
// This doesn't work. Nothing is initiated.
TcpServer.DefaultPort := 5000;
TcpServer.Active := True;
Log('Server started on port ' + IntToStr(TcpServer.DefaultPort));
Commands.LogProc := @Log;
Log('Commands.LogProc created');
end;
procedure TForm1.btnStartClick(Sender: TObject);
begin
// This works perfectly fine.
TcpServer.DefaultPort := 5000;
TcpServer.Active := True;
Log('Server started on port ' + IntToStr(TcpServer.DefaultPort));
Commands.LogProc := @Log;
Log('Commands.LogProc created');
end;
procedure TForm1.Log(const S: string);
begin
MemoLog.Lines.Add(FormatDateTime('hh:nn:ss', Now) + ' ' + S);
end;
Second unit:
unit Commands;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IdContext, IdGlobal;
type
TLogProc = procedure(const S: string) of object;
var
LogProc: TLogProc; // <-- set from Unit1
procedure HandleCommand(AContext: TIdContext; const Cmd: string; const Data: TBytes);
implementation
procedure Test(AContext: TIdContext; const Data: TBytes);
var
ClientVersion, UserID: LongInt;
DataToSend: TIdBytes;
begin
LogProc('We are in the Test procedure');
end;
Why do neither the server nor the Log procedure work without pressing the button?
What's more, if I try to connect from the client, the program crashes. But not after I press the Start button.
The exact same code that’s in btnStart is also in FormCreate (I also tried FormShow with the same result), but it seems like the program is ignoring what’s in FormCreate.
I'll be grateful for an explanation and a solution.
Cheers
I forgot to mention. Calling Log from Unit1 works fine, no need to press the Start button.