Skip to content

Instantly share code, notes, and snippets.

Created Jan 18, 2012
What would you like to do?
Extension method for calculating the usable client area of a control
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
public static class Meh
private static readonly IDictionary<DockStyle, Func<Control, Point>> DockAdjusters = new Dictionary<DockStyle, Func<Control, Point>>
{DockStyle.Top, c => new Point(0, c.Height)},
{DockStyle.Left, c => new Point(c.Width, 0)},
{DockStyle.Bottom, c => new Point(0, -c.Height)},
{DockStyle.Right, c => new Point(-c.Width, 0)},
{DockStyle.Fill, c => new Point(Int32.MaxValue, Int32.MaxValue)} // won't be any intersection => empty!
/// <summary>
/// Creates a copy of this rectangle.
/// </summary>
public static Rectangle Copy(this Rectangle r)
return new Rectangle(r.Location, r.Size);
/// <summary>
/// Creates a new rectangle that is a copy of this rectangle but whose location
/// is adjusted by the specified amount expressed as a point.
/// </summary>
public static Rectangle OffsetCopy(this Rectangle r, Point pt)
var copy = r.Copy();
return copy;
/// <summary>
/// Calculates the usable client area of this control, defined as the client rectangle
/// minus the space occupied by docked child controls.
/// </summary>
public static Rectangle UsableClientArea(this Control control)
var usableArea = control.ClientRectangle.Copy();
foreach (var ctrl in control.Controls.Cast<Control>().Where(c => c.Dock != DockStyle.None))
var pt = DockAdjusters[ctrl.Dock](ctrl);
usableArea = Rectangle.Intersect(usableArea, usableArea.OffsetCopy(pt));
if (usableArea.IsEmpty)
return usableArea;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment