简体   繁体   中英

Resizing C# Windows Form

Not sure if this is the standard way of creating a form and opening, but the code the below does display the form properly. My problem is that I can't programatically change it's size. I'm guessing it has to do with the scope, "main" creates the form object, but I'd like to be resize it in the scope where it actually gets initialized (instead of in the [Design] tab of MS Studio) but I can't find the object/handle to it!

main.cs:
class MainProgram
{
    static void Main(string[] args)
    {
        // Create Form Object and Open Gui for user
        MainForm newFrm = new MainForm();   // Mainform is type Systems.Windows.Forms.Form
        Application.Run(newFrm); 
    }
}

formFile.cs:
public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        //TODO: How to Resize Form from here?
        //this.Size.Height = 100; // ERROR!
    }
}

You could change the Size with this code

  this.Size = new System.Drawing.Size(this.Size.Width, 100); 

Size is a Struct not a Class. This means that it is a Value type. When you try to change one of its properties the rules of the language force the compiler to create a copy of the original structure and you change the property of the copy not of the original structure.

More details at MSDN

Choosing between Class and Struct

The way you're changing form size it's wrong. You should use System.Drawing.Size

using System.Drawing;

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        this.Size = new Size(this.Size.Width, 100); 
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM