Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set minimum window size in C# .NET

Tags:

c#

.net

winforms

I am having trouble setting the minimum size of my window in a C# application I am working on. I have tried this code in the form's constructor:

this.MinimumSize.Width = 800;
this.MinimumSize.Height = 600;

But the compiler says:

Cannot modify the return value of 'System.Windows.Forms.Control.MinimumSize' because it is not a variable

Can anybody shed some light on this issue for me?

EDIT:

Using:

this.MinimumSize = new Size(800,600);

Gives:

 error CS0118: 'System.Windows.Forms.Form.Size' is a 'property' but is used like a 'type'

Sorry I forgot to mention that I had already tried that. Also forgot to mention that I am not using Visual Studio.

like image 943
Dai Avatar asked Mar 15 '11 15:03

Dai


4 Answers

Since Size is a struct, you can't do that.
Instead, you need to assign a new Size value to the property, like this:

this.MinimumSize = new Size(800, 600);

EDIT Your compiler is wrong; it's confusing the Size class with the Control.Size property.

To work around this unjust error, you need to qualify the type with a namespace:

this.MinimumSize = new System.Drawing.Size(800, 600);

Or you just forgot using System.Drawing.

like image 190
SLaks Avatar answered Oct 23 '22 23:10

SLaks


You should use something like this:

this.MinimumSize = new Size(100, 100);

Width and Height are used to get the existing values instead of setting them.

If you go to the definition of MinimumSize, you will see this:

public override Size MinimumSize { get; set; }

Once again confirming that even when you decide to set the value for it, you have to pass an actual Size instance. Width and Height are properties strictly tied to the Size instance.

like image 24
Den Delimarsky Avatar answered Oct 23 '22 21:10

Den Delimarsky


This is the compiler error:

http://msdn.microsoft.com/en-us/library/wydkhw2c(VS.71).aspx

The basic problem is that the MinimumSize member property returns a struct - which is a value type - and so is copied into a local temporary variable - and this prevents you from writing a value back to the underlying property.

To get around this, you need to assign to MinimumSize itself:

this.MinimumSize = new Size(800, 600);
like image 4
Stuart Avatar answered Oct 23 '22 22:10

Stuart


You need to assign directly to the MinimumSize property:

this.MinimumSize = new Size(800, 600);

Basically, the return value of the MinimumSize property is always a new struct object; the compiler doesn't let you assign to this temporary value (as stated in the error, it's not a variable).

This MSDN Social thread is most enlightening about the subject.

like image 3
Cameron Avatar answered Oct 23 '22 22:10

Cameron