Starting with VB5, the Show method supports a second optional argument, that lets you specify which form owns the form that is about to be displayed:
Form2.Show , Me
A owned form is always displayed in front of its owner, and when the owner is unloaded, VB automatically unloads the owned form as well. The second argument is mostly used only when the form is being displayed not modally, because modal forms are always displayed in front of their owners.
The problem with this approach, however, is that it can’t work with forms contained in ActiveX DLLs and EXEs, because form references don’t work across project boundaries. The answer is the following API function:
Private Declare Function SetWindowLong& Lib "user32" Alias "SetWindowLongA" _ (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long)Const GWL_HWNDPARENT = (-8)Function SetOwner(ByVal HwndtoUse, ByVal HwndofOwner) As Long SetOwner = SetWindowLong(HwndtoUse, GWL_HWNDPARENT, HwndofOwner)End Function
The SetOwner function returns the handle of the previous owner of the window, so you must restore it before exiting. In the following example this function is used with a form included in the current project, but you can easily extend it to work with forms from other applications. The only thing to do is letting the external application have the hWnd of the form in the main application that must become the owner window:
Dim frm As Form2Dim oldOwner As LongPrivate Sub cmdShowForm_Click() ' show the form Set frm = Form2 frm.Show ' make it owned by the current form oldOwner = SetOwner(frm.hwnd, Me.hwnd)End SubPrivate Sub cmdUnloadForm_Click() ' restore original owner SetOwner frm.hwnd, oldOwner ' unload the form Unload frmEnd Sub