C# Programming > Windows Forms

C# Bind Window to Screen

Screen Bounds

There is no automatic way to bind a Window to the Screen in C#. However you can make use for Window Form properties and events to force a window to stay inside the screen at all times.

LocationChanged

Since a Windows Form moves around with the titlebar, programmers can only keep track of where the Form is being moved to. Thus you use the LocationChanged event to monitor when the Form is being dragged by the user.

Knowing the bounds of the screen, whether it is the single primary screen or all screens combined, can be accomplished through the C# Screen class provided by the .NET Framework.

To bind the Window to the screen simply check the four edges of the Form and correct the position if any of them is outside the screen:

private void Form1_LocationChanged(object sender, EventArgs e)
{
      if (this.Left < 0)
           this.Left = 0;
      else if (this.Right > Screen.PrimaryScreen.Bounds.Width)
           this.Left = Screen.PrimaryScreen.Bounds.Width - this.Width;
      
      if (this.Top < 0)
           this.Top = 0;
      else if (this.Bottom > Screen.PrimaryScreen.Bounds.Height)
           this.Top = Screen.PrimaryScreen.Bounds.Height - this.Height;
}

Draggable Window

The only problem with the C# code above is that the Form will sometimes flicker when it is moved back into place. A way to solve this would be by handling the Form dragging ability yourself. That way you can cleanly bind the window to the screen.

Back to C# Article List