How to check if a child window exists?

I have a main form (MainForm) and an MDI child window (TFormChild). I want to create several forms of TFormChild, but the first should behave in a certain way, so I need to determine if the TFormChild window exists.

I use this code, but it does not work:

function FindChildWindowByClass(CONST aParent: HWnd; CONST aClass: string): THandle; begin Result:= FindWindowEx(aParent, 0, PChar(aClass), NIL); end; 

I call it this way:

 Found:= FindChildWindowByClass(MainForm.Handle, 'TFormChild')> 0; 
+6
source share
3 answers

Name it like

 Found:= FindChildWindowByClass(MainForm.ClientHandle, 'TFormChild')> 0; 

MDI child windows are child elements of 'MDICLIENT' , the ClientHandle property TCustomFrom contains a handle.

+7
source

In the form, you can reference the MDIChildCount and MDIChildren properties.

eg:

 var i: integer; begin for i:= 0 to MainForm.MDIChildCount-1 do begin if MainForm.MDIChildren[i] is TFormChild then ... end; ... end; 
+13
source

The best way to achieve this is to have the form you want to open in order to check if it exists. To do this, your form must declare a class procedure. Declared as a class procedure, proc can be called regardless of whether the form exists or not.

Add to your form in the public section

 class procedure OpenCheck; 

then the procedure looks like this:

 Class procedure TForm1.OpenCheck; var f: TForm1; N: Integer; begin F := Nil; With Application.MainForm do begin For N := 0 to MDIChildCount - 1 do begin If MDIChildren[N] is TForm1 then F := MDIChildren[N] as TForm1; end; end; if F = Nil then //we know the form doesn't exist //open the form as the 1st instance/add a new constructor to open as 1st else //open form as subsequent instance/add new constructor to open as subsqt instance end; 

Add Form1 module to your mdiframe uses clause.

To open a form, call the class procedure, which in turn will call the form constructor.

 TForm1.OpenCheck; 

One warning word using class procedures does not have access to any form components / properties. Since the form should not actually be created, access to them will lead to violation of access rights, that is, until you find out that F is not equal to zero. You can then use F. to access the components / properties of the form.

+3
source

Source: https://habr.com/ru/post/893684/


All Articles