Find Delphi component by string

2

I need to open a form in Delphi , but instead of calling it direct by the name UniForm1 , I need to call it by the value stored in a String p>

procedure TMainForm.UniTreeView1Change(Sender: TObject; Node: TUniTreeNode);
var nome : string;
    tela : TUniForm;
begin
   nome := Node.Text;
   tela := FindComponent(nome) as TUniForm;

   //UniPanel1.Caption := nome;

   tela.Parent := UniPanel1;
   tela.Show;
   tela.SetFocus;
end;

However, when I select an item in TreeView , the following error occurs and does not open the form:

  

Project Log_Project.exe raised exception class $ C0000005 with message   'access violation at 0x006d0f13: read of adress 0x000003ce'.

    
asked by anonymous 15.09.2017 / 19:41

1 answer

4

As said by @Tiago Rodrigues, the form you are looking for is probably not within that other form . Within Application you have this same function FindComponent , you can use it to find your form .

tela := Application.FindComponent(nome) as TUniForm;

At this point you're not sure if the form you're looking for was found, so ideally you should make sure it was actually found before doing anything with it.

if (tela <> nil) then
  begin
    tela.Parent := UniPanel1;
    tela.Show;
    if (tela.Showing) then
      tela.SetFocus;
  end;

Just one more thing, before giving SetFocus to any component, make sure it is showing with the Showing property. If this property returns True , it means that the component is being displayed, if it returns False , the component is not being displayed. This check is required because if the component is not being displayed the program will throw an exception. When the component is not a form , I usually also check that the Enabled of it is not False , so I should give SetFocus .

    
18.09.2017 / 13:50