Creating a New Form of the Specified Type

Mikecrosoft
03-25-2004, 07:42 AM
This code its used to create new forms (or another types) just passing the Type of the form, this was done using a method called InvokeMember of the Type Class, this method calls the constructor of the specified Type and returns a new instance of it. So I used this code for my MDI application, this function searches for a opened window of one Type, if there is opened window, just returns that window, but if the window type is not found, return a new one. I hope help.



Public Function SearchWindow(ByVal MyFormType As Type, ByVal ParentWindow As Form) As Form

'Check if the MyFormType is a Window
If Not MyFormType.BaseType.Equals(GetType(Form)) Then
MsgBox("MyFormType is not a Window")
Exit Function
End If

Dim Frm As Form

'Searches in the MDIParent object if one instance of the specified form
'is opened, if yes return it.
For Each Frm In ParentWindow.MdiChildren
If Frm.GetType.Equals(MyFormType) Then
Return Frm
End If
Next

'If any form was found, so created a newone form on the specified type ;)
Dim NewFrm As Object = MyFormType.InvokeMember(Nothing, Reflection.BindingFlags.DeclaredOnly Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.CreateInstance, Nothing, Nothing, Nothing)

'Return the new form
Return NewFrm

End Function


Thanks :)

Mike

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum