How to make my Windows Form app snap to screen edges?

erator picture erator · Feb 26, 2009 · Viewed 24k times · Source

Anyone out there know how to make your .net windows form app sticky/snappy like Winamp so it snaps to the edges of the screen?

The target framework would be .NET 2.0 Windows Form written in C#, using VS08. I am looking to add this functionality to a custom user control, but I figured more people would benefit from having it described for the application and its main form.

Thank you.

Answer

Hans Passant picture Hans Passant · Feb 26, 2009

This worked pretty well, works on multiple monitors, observes the taskbar:

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
    }
    private const int SnapDist = 100;
    private bool DoSnap(int pos, int edge) {
      int delta = pos - edge;
      return delta > 0 && delta <= SnapDist;
    }
    protected override void  OnResizeEnd(EventArgs e) {
      base.OnResizeEnd(e);
      Screen scn = Screen.FromPoint(this.Location);
      if (DoSnap(this.Left, scn.WorkingArea.Left)) this.Left= scn.WorkingArea.Left;
      if (DoSnap(this.Top, scn.WorkingArea.Top)) this.Top = scn.WorkingArea.Top;
      if (DoSnap(scn.WorkingArea.Right, this.Right)) this.Left = scn.WorkingArea.Right - this.Width;
      if (DoSnap(scn.WorkingArea.Bottom, this.Bottom)) this.Top = scn.WorkingArea.Bottom - this.Height;
    }
  }