RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB4/32,VB5,VB6
Expertise: Intermediate
Aug 21, 1999

Create a owner form with API functions

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)

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 Form2
Dim oldOwner As Long

Private Sub cmdShowForm_Click()
    ' show the form
    Set frm = Form2
    ' make it owned by the current form
    oldOwner = SetOwner(frm.hwnd, Me.hwnd)
End Sub

Private Sub cmdUnloadForm_Click()
    ' restore original owner
    SetOwner frm.hwnd, oldOwner
    ' unload the form
    Unload frm
End Sub
Michael Muriph
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date