Question

I have an object called eventsobj. In one of its procedures It draws a few dynamic images onto a form. So far it works. However for neatness and because my teacher told me to my object is in a separate unit.

What I would ideally like is for the object to have a function that returns a TForm, which I will then set to the main form. In my other unit:

    Function drawNewForm(numberOfImages : integer) : TForm1;

In my main form:

    NewForm := TForm1.create;
    NewForm := drawNewForm(10);
    CurrentForm := newform;

Sorry it's vague but all I need is the principle not necessarily the code. When I tried these few lines the current form didn't change at all.

Thanks in advance for the help.

Was it helpful?

Solution

I don't think your teacher will be satisfied if you just move everything (including the form) to a new unit... you could as well rename the unit. hehehe.

I believe what your teacher meant is that your eventsobj class should be in another unit, and you should instantiate it in your main form. You would have something like this:

YourNewUnit.pas:

unit YourNewForm;

...

type
  TYourClass = class(...)

...

MainForm.pas:

unit MainForm;

interface

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

...

procedure TForm1.FormCreate(Sender: TObject);
begin
    with TYourClass.Create(Self) do begin
        Parent := Self; //If needed...
        //Other initialization stuff
    end;
end;

You could also create a private field on the form to hold the reference to your TYourClass instance if you need to call it later on the code. This would look like this:

unit MainForm;

interface

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

type
    TForm1 = class(TForm)
    private
        FYourClass: TYourClass;

...

procedure TForm1.FormCreate(Sender: TObject);
begin
    FYourClass := TYourClass.Create(Self);
    with FYourClass do begin
        Parent := Self; //If needed...
        //Other initialization stuff
    end;
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top