我无法有条件地从Main()更改Windows窗体的大小

当我从事新的Windows窗体项目时,我只是意识到我无法更改窗体以及该窗体属性中的其他所有内容。代码没有错误,但是没有任何变化。

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Form1 a = new Form1();
    Application.Run(a);
    //this is where program happen and at some point in this program i want to
    //change the size of the form
    a.Size = new System.Drawing.Size(40,40);                                               
}

所以我只想直接在Main()中有条件地更改表单,文本框等的任何属性。谢谢!

XZ345786 回答:我无法有条件地从Main()更改Windows窗体的大小

在运行应用程序之前,先更改其大小,首先更改窗体的大小,然后执行input string: CAAGGA ColF (Column from): 46 ColT ( Column To ): 51

Species Matchs
LL  6
MM  5
PP  4
,

您在此处面临的问题是Application.Run()是一项阻止操作。如果您在调试器中逐步执行代码,您将注意到,在调用Application.Run()之后,线程将不会返回(继续调整大小),直到关闭窗体为止。

这意味着如果要在运行应用程序时更改其大小,则可以选择执行以下操作的方法:

  1. 来自Form类本身:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            //In the constructor
            this.Size = new Size(100,100);
        }
    
        //Or in an event
        private void Form1_Load(object sender,EventArgs e) => this.Size = new Size(100,100);
    }
    
  2. 来自另一个线程
    警告:如果您沿着这条路走,则在更改任何UI元素的属性时以及从那里更改时都必须非常小心。请仔细阅读CrossThreadCalls(https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.checkforillegalcrossthreadcalls?view=netframework-4.8)的含义

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
    
            Form1 frm1 = new Form1();
    
            //If you really need to go down this road read up on what this is doing
            Control.CheckForIllegalCrossThreadCalls = false;
    
            new Thread(new ThreadStart(() =>
            {
                Random rng = new Random();
    
                while(true)
                {
                    frm1.Size = new System.Drawing.Size(rng.Next(50,1000),rng.Next(50,1000));
    
                    Thread.Sleep(2000);
                }
            })).Start();
    
            Application.Run(frm1);
        }
    }
    
本文链接:https://www.f2er.com/3168645.html

大家都在问