假设我现定义了若干个类似为aForm,bForm,cForm......的Form名称,并把他们存放于数据库的一个字段中,当从数据库中取出到DBGrid中时我可以通过双击某行用下面的语句创建窗体:
       aForm:=TaForm.Create(self);
       aForm.showmodal;
       aForm.free;
我想动态的传递窗体名称,但我不知道窗体类该如何得到(TaForm),请问我这个函数应该怎么写。

解决方案 »

  1.   

    function FindClass(const ClassName: string): TPersistentClass;
      

  2.   

    A Button Class to Automatically Create Forms
    This example creates a handy button component that can be used to automatically create and show forms. It uses properties and events to set the form name and to show the form modally.We're essentially using the same approach that Delphi uses in the Application.CreateForm method. If you have the VCL source you might want to check it out.To dynamically create an object using a text string of its class name, you need to first obtain an object-type reference. This can be done using the FindClass or GetClass functions. These return a TPersistentClass type. To create forms on the fly, you need to recast this as a TFormClass.Once you have this class reference you can use Application.CreateForm or the Create method to create a new object, for example:var
      FormName: string;
      AForm: TForm; 
    begin
      Application.CreateForm(TFormClass(FindClass('T'+FormName)), AForm);
    end; 
    There is one catch to using FindClass. Before your class can be found it needs to be registered with Delphi, otherwise you get a "Class ... not found" error. The best place to register the class is in the unit that defines the class. Include the following code in the initialization section at the end of the unit: initialization
     RegisterClass(TForm2); 
    end. 
      

  3.   

    For a button component, we might want to modify this to make the button the owner of the form. The following extract from our finished component adds the following code to the button's Click method: procedure TFormButton.Click; 
    var
      AClass: TPersistentClass;
      AFormClass: TFormClass; 
    begin
      inherited Click;
      if FFormName = '' then Exit;
      if FForm = nil then
      begin
        AClass := FindClass('T' + FFormName);
        AFormClass := TFormClass(AClass);
        FForm := AFormClass.Create(Self);
      end;
      if FShowModal then
        FFormModalResult := FForm.ShowModal
      else
        FForm.Show;
      if Assigned(FAfterShow) then FAfterShow(Self);
    end; 
    You can see we've also added some properties and code to show the form either modal or non-modal, and to execute an event after showing the form. This event is essential for a modal form where you want to do something after the form is hidden or destroyed.The full component source includes additional runtime properties and methods to access the form.http://www.obsof.com/delphi_tips/delphi_tips.html