Link to home
Start Free TrialLog in
Avatar of gspears060598
gspears060598

asked on

How to get a form handle/variable

Hi,

I have an MDI application.  I guarantee that each MDIChild window can only have one copy open at a time.  Within the code of the window, I need to do things or check things related to that window.  For example, I need to check if the window is visible.

I would normally do this with...
 if MyForm.Visible = true ...

Then question is:  Is there an easy way to get 'MyForm'.
MyForm is a variable of type TMyForm.  I know that when I look at the source code for the window, I have a variable declaration of
  MyForm : TMyForm;

but this is not set to anything.  I need to set it to a valid value.  I can do this with this code...

// Create a handle to the Current Window
  ThisWindow := nil;
  with Application.MainForm do
    for N := 0 to MDIChildCount - 1 do
      if MDIChildren[N] is TMyForm then
        ThisWindow := MDIChildren[N] as TMyFormF;

Isn't there an easier way to do this?

Please respond to gman@mics.net
Avatar of heathprovost
heathprovost
Flag of United States of America image

var
  N: Integer;
begin
  with Application.MainForm do
    for N := 0 to MDIChildCount - 1 do
    begin
      if not (MDIChildren[I] is TMyForm) then continue;
      with TMyForm(MDIChildren[I]) do
      begin
        //do whatever
      end;
    end;
end;

This isnt much better, but it will run a little faster due to the removal of the second type check (the as).  TypeCasting this way is much faster and you are already typechecking with the is statement.
Code correction -

var
  N: Integer;
begin
  with Application.MainForm do
    for N := 0 to MDIChildCount - 1 do
    begin
      if not (MDIChildren[N] is TMyForm) then continue;
      with TMyForm(MDIChildren[N]) do
      begin
        //do whatever
      end;
    end;
end;
This would be even faster...

.....
ThisWindow := TMyFormF(MDIChildren[N]);
....

so that's not a solution also....

I don;t understand are you trying to see if a window is visible or if it is of the same type?!?!

-Viktor
-Ivanov
ASKER CERTIFIED SOLUTION
Avatar of rwilson032697
rwilson032697

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of adeng
adeng

Have you try this :

1. After you make a new form in delphi IDE, goto menu : Project | Option : and remove MyForm from 'Auto-Create forms' List Box.

2. write this code :

procedure TMyForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
     Action := caFree;
end;

procedure TMyForm.FormDestroy(Sender: TObject);
begin
     MyForm := nil;
end;

3. Use this code to make MyForm visible and prevent multiple copy :

procedure TForm1.Button1Click(Sender: TObject);
begin
       if not assigned(MyForm) then      
            MyForm := TMyForm.Create(Application);
       MyForm.Show;
end;

Regards Adeng;