Sunday, November 23, 2008

Full screen forms in .NET

Today I tried to make a form take up the whole screen (including the taskbar) in C# on the .NET platform. .NET WinForms does not offer functionality to do this, so I nosed around the web. All results that I found used platform-dependent P/Invoke calls to accomplish this goal. However, I wanted to keep my code platform-independent, so I created a pure, managed .NET solution.

First, we need some member variables to remember the window state, so we can come back out of full screen mode:

private FormWindowState m_previousWindowState;
private Bounds m_previousBounds;
private FormBorderStyle = m_previousBorderStyle;

The code to switch into full screen mode then becomes:

m_previousBorderStyle = FormBorderStyle;
m_previousWindowState = WindowState;
m_previousBounds = Bounds;
// Stay on top of everything else.
TopMost = true;
// Remove the window border.
FormBorderStyle = FormBorderStyle.None;
// We cannot change the Bounds of a maximized form.
WindowState = FormWindowState.Normal;
// Set the size of the form to the size of its screen.
Bounds = Screen.FromControl(this).Bounds;

The code to switch back simply restores all this:

TopMost = false;
FormBorderStyle = m_previousBorderStyle;
WindowState = m_previousWindowState;
Bounds = m_previousBounds;

It's really quite simple, and I don't know why people make it more complex than it should be.

1 comment:

Anonymous said...

Hi Thomas,

Great stuff dude. It's very neat approach. Thanks Buddy.