Simple full screen support in Windows Forms

These simple steps lets you create a Windows Forms application with full screen support. I have changed the DoubleBuffered property to true for flicker free redrawing, StartPosition to Manual to be able to manage startup position in code and KeyPreview to true.

This code in the Load event handler will position the window and restore the fullscreen state.

var s = this.GetScreen();
this.Top = s.WorkingArea.Top + 40; this.Left = s.WorkingArea.Left + 40;
this.Width = s.WorkingArea.Width - 80; this.Height =
                                             s.WorkingArea.Height - 80;
if ((Application.UserAppDataRegistry.GetValue("Fullscreen",
                                         "false") as string) == "true")
   this.ToggleFullscreen();

This is the KeyDown event handler that will enable the user to press F11 or Alt+Enter to toggle fullscreen.

private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
   if(((e.KeyCode == Keys.Enter) && e.Alt) || (e.KeyCode == Keys.F11))
      this.ToggleFullscreen();
}

The FormClosing event handler stores the screen state:

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
   if (this.FormBorderStyle ==
                        System.Windows.Forms.FormBorderStyle.Sizable)
      Application.UserAppDataRegistry.SetValue("Fullscreen", "false");
   else
      Application.UserAppDataRegistry.SetValue("Fullscreen", "true");
}

And here are the GetScreen and ToggleFullscreen functions:

private Screen GetScreen()
{
   var s = Screen.FromPoint(new Point((int)(this.Left + (this.Width / 2)),
                                    (int)(this.Top + (this.Height / 2))));
   return s ?? Screen.PrimaryScreen;
}

private void ToggleFullscreen()
{
   var s = this.GetScreen();
   if (this.FormBorderStyle ==
       System.Windows.Forms.FormBorderStyle.Sizable)
   {
      this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
      this.Top = s.Bounds.Top;
      this.Left = s.Bounds.Left;
      this.Width = s.Bounds.Width;
      this.Height = s.Bounds.Height;
   }
   else
   {
      this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
      this.Top = s.WorkingArea.Top + 40; this.Left =
         s.WorkingArea.Left + 40;
      this.Width = s.WorkingArea.Width - 80; this.Height =
         s.WorkingArea.Height - 80;
   }
 }

Finally, the Resize event handler should invalidate the form, and the Paint event handler should contain the drawing instructions.

Leave a Reply

Your email address will not be published. Required fields are marked *