Search code examples
c#winformsminimizemaximize-window

Maximizing a form, and disabling user to resize the form


I am trying to create a form that is maxed out, without allowing the user to resize it. I tried to maximize the FormWindowState, and remove the minimize and maximize button. By setting this.MimimumSize and this.MaximumSize to this.Size (the maximized size), this should account to a maximized form.

Yet, when I run it, the form becomes a really small square. Any thoughts on how I can fix this?

public partial class Testscherm : Form
{
    public Testscherm()
    {
        this.WindowState = FormWindowState.Maximized;
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
        this.MinimumSize = this.Size;
        this.MaximumSize = this.Size;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        InitializeComponent();
    }
}

Solution

  • Try calling InitializeComponent() first, then add any statements which changes attributes/properties of the form. Otherwise, the designer generated code may undo any of changes you did beforehand.

    Second, Form.Size does not deliver the form's size in maximized state. You could instead iterate over

    System.Windows.Forms.Screen.AllScreens
    

    then get the actual screen size along the lines of

    System.Windows.Forms.Screen.AllScreens.First().WorkingArea.Size;
    

    and assign it to this.Size;

    Another problem here is, as soon as you assign this, this.MaximizeBox = false, Winforms forbids WindowState to be FormWindowState.Maximized. This is obviously "by design". What you probably want here is to use

     this.FormBorderStyle = FormBorderStyle.None;
    

    which does not only remove the maximum and minimum buttons, but also the close button. If you need such button, consider to add your own close button to the window.

    Putting this all together gives

            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
            this.FormBorderStyle = FormBorderStyle.None;
            this.Size = System.Windows.Forms.Screen.AllScreens.First().WorkingArea.Size;
            this.MinimumSize = this.Size;
            this.MaximumSize = this.Size;
    

    But: are you sure it is a good idea what you are trying there? How will this behave on a machine with two monitors of different resolution for example? It may be ok for a program which uses specific hardware and works as a dedicated software which takes over the machine exclusively (something like a Kiosk mode). Note the window may still be moved around using certain Win-<Key> keyboard shortcuts.