Jerry Nixon @Work: "Dock" a WinForm beside another WinForm

Jerry Nixon on Windows

Friday, March 14, 2008

"Dock" a WinForm beside another WinForm

This code sort of "docks" a WinForm to the left side of another. When you see what I am doing, you will see that this is actually pretty simple. It's a cool look and you can change it in your own way to dock to top/right/bottom. There's nothing to do on the "parent" form and here's the code for the "child" form:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public partial class ChildForm : Form
{
Form m_ParentForm;
public ChildForm(Form parentForm)
{
InitializeComponent();
m_ParentForm = parentForm;

// setup

m_ParentForm.Left = m_ParentForm.Left + (this.Width / 2);
Reposition(null, null);
m_ParentForm.Activated += new EventHandler(Reposition);
m_ParentForm.Move += new EventHandler(Reposition);
m_ParentForm.ResizeEnd += new EventHandler(Reposition);
m_ParentForm.FormClosing += new FormClosingEventHandler(ParentForm_FormClosing);
this.FormClosing += new FormClosingEventHandler(ChildForm_FormClosing);
}

void ChildForm_FormClosing(object sender, FormClosingEventArgs e)
{
m_ParentForm.Activated -= new EventHandler(Reposition);
m_ParentForm.Move -= new EventHandler(Reposition);
m_ParentForm.ResizeEnd -= new EventHandler(Reposition);
m_ParentForm.FormClosing -= new FormClosingEventHandler(m_ParentForm_FormClosing);
}

void ParentForm_FormClosing(object sender, FormClosingEventArgs e)
{
this.Close();
}

void Reposition(object sender, EventArgs e)
{
this.Height = m_ParentForm.Height;
this.Top = m_ParentForm.Top;
this.Left = m_ParentForm.Left - this.Width - 5;
// z index
SetWindowPos((int)this.Handle,
(int)m_ParentForm.Handle,
0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOACTIVATE);
}

[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
public static extern bool SetWindowPos(
int hWnd, // window handle
int hWndInsertAfter, // placement-order handle
int X, // horizontal position
int Y, // vertical position
int cx, // width
int cy, // height
uint uFlags); // window positioning flags
const uint SWP_NOSIZE = 0x1;
const uint SWP_NOMOVE = 0x2;
const uint SWP_SHOWWINDOW = 0x40;
const uint SWP_NOACTIVATE = 0x10;
}