//Listing 1

protected override void OnMove(EventArgs e)
{
  Rectangle form = this.Bounds;
  Rectangle screen = Screen.FromHandle(this.Handle).Bounds;
  if (!screen.Contains(form))
  {
    int left = form.Left;
    int top = form.Top;
    if (form.Right > screen.Right)
      left = screen.Right - form.Height;
    if (form.Bottom > screen.Bottom)
      top = screen.Bottom - form.Height;
    if (left < screen.Left)
      left = screen.Left;
    if (top < screen.Top)
      top = screen.Top;
    //reposition the form
    this.Location = new Point(left, top);
    if ((form.Width > screen.Width) ||
        (form.Height > screen.Height))
    {
      this.Size = new Size(Math.Min(form.Width,
        screen.Width), Math.Min(form.Height,
        screen.Height));
    }
  }
  base.OnMove(e);
}

//Listing 2

private const int WM_MOVING = 0x0216;

protected override void WndProc(ref Message m)
{
  base.WndProc(ref m);
  if (m.Msg == WM_MOVING)
  {
    RECT data = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));
    Rectangle realData = (Rectangle)data;
    if (OnFormMoving(ref realData))
    {
      Marshal.StructureToPtr((RECT)realData, m.LParam, false);
    }
  }
}

protected bool OnFormMoving(ref Rectangle destination)
{
  Rectangle result = new Rectangle(100, 200, 500, 100);
  destination = result;
  return true;
}

//Listing 3

[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
  private int left;
  private int top;
  private int right;
  private int bottom;

  public int Left
  {
    get { return this.left; }
    set { this.left = value; }
  }
  public int Top
  {
    get { return this.top; }
    set { this.top = value; }
  }
  public int Right
  {
    get { return this.right; }
    set { this.right = value; }
  }
  public int Bottom
  {
    get { return this.bottom; }
    set { this.bottom = value; }
  }

  public RECT(int left, int top, int right, int bottom)
  {
    this.left = left;
    this.top = top;
    this.right = right;
    this.bottom = bottom;
  }

  public static explicit operator Rectangle(RECT r)
  {
    return Rectangle.FromLTRB(r.Left, r.Top, r.Right, r.Bottom);
  }

  public static explicit operator RECT(Rectangle r)
  {
    return new RECT(r.Left, r.Top, r.Right, r.Bottom);
  }
}

//Listing 4

Rectangle desktop = Screen.FromPoint(MousePosition).Bounds;
Rectangle manipulate = destination;
//Block if an edge is close to the edge of the screen.
if (desktop.Left > manipulate.Left)
    manipulate.X = desktop.Left;
if (desktop.Top > manipulate.Top)
    manipulate.Y = desktop.Top;
if (desktop.Right < manipulate.Right)
    manipulate.X = desktop.Right - manipulate.Width;
if (desktop.Bottom < manipulate.Bottom)
    manipulate.Y = desktop.Bottom - manipulate.Height;
if (manipulate != destination)
{
    destination = manipulate;
    return true;
}
else
    return false;