Visual Basic 6.0: Docking a Child Form Inside a Parent Form With SetParent.

June 10, 2010

This is a quick and easy example of how to dock the contents from a child form into a parent form.

You can see Window docking functionality in the Visual Basic 6.0 IDE if you drag a floating tool window (like the ToolBox, Project Explorer, Properties Editor, or Immediate) to one of the edges of the IDE. The window will snap to the edge and become docked with the main IDE window.

It’s actually very easy to place the contents from one form or container control into another one.

To start, create a new “Standard EXE” project in Visual Basic 6.0. Add a new standard Form (which will be the parent) and create a new PictureBox control on it. Set the Align property of the PictureBox to any direction (vbAlignTop, vbAlignBottom, vbAlignLeft, or vbAlignRight) so that it automatically negotiates and snaps to the edge of the form. Then create another standard form (which will be the child) and with whatever controls you’d like on it.

We will use the following API declarations:

Public Declare Function SetParent Lib "user32" (ByVal hWndChild As Long, ByVal hWndNewParent As Long) As Long
Public Declare Function GetParent Lib "user32" (ByVal hwnd As Long) As Long

These can be declared either as public within a shared module, or as private within any forms that call them. If you include the Windows API Type Library as a reference in your project, they will be automatically declared.

GetParent allows us to obtain the handle of an object’s parent. SetParent allows us to change an object’s parent container. Both functions take the hWnd of a form or control as input. GetParent takes the hWnd of the child container and returns the hWnd of it’s current parent. SetParent takes the hWnd of the child container as the first parameter and the hWnd of the new parent container as the second parameter, then returns the hWnd of the previous  parent on success.

Placing the contents of “Form2” into the “PictureBox1” control on “Form1” it is as easy as:

Call SetParent(Form2.hWnd, Form1.PictureBox1.hWnd)

Add this to the Form_Load event of your parent form along with a line to make the child form visible (either Form2.Show or Form2.Visible = True). You should see the form appear inside the picture box on the parent form.

Of course there is still a lot to be done before the window will work like it does in the Visual Basic IDE. You can move the child window around within the PictureBox and change it’s state. You cannot resize the picture box that contains the form by grabbing it’s edge. You also cannot drag the child form back out of the dock or to another side. All of this functionality will have to be coded and can be done in a few different ways.

I may discuss some of them in another post. This one is just a basic example which should give you an idea of how to get started.