Closing a form during a constructor

前端 未结 9 1940
面向向阳花
面向向阳花 2020-12-01 11:59

Is it possible to close a form while the constructor is executing (or simply to stop it showing at this stage)?

I have the following code:

public par         


        
相关标签:
9条回答
  • 2020-12-01 12:28

    Can you make MyFunc static? and then do something like:

    static void Main() 
    {             
        ... 
        if (MyForm.MyFunc())
        {
            Application.Run(new MyForm()); 
        }
    } 
    

    this would essentially give you the same control over whether the form is going to be constructed or not?

    0 讨论(0)
  • 2020-12-01 12:28

    I found adding a handler to the 'Load' event is better as this way the dialog is never displayed at all. With the 'Shown' event you might briefly see the dialog open and then close which may be confusing:

    public partial class MyForm : Form
    {        
        public MyForm()
        {
            if (MyFunc())
            {
                this.Load += MyForm_CloseOnStart;
            }
        }
    
        private void MyForm_CloseOnStart(object sender, EventArgs e)
        {
            this.Close();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 12:29

    When you call Close() on a form, internally it is disposing of the form and releasing any managed resources. When you do this:

    Application.Run(new MyForm());
    

    You'll likely get an ObjectDisposedException. What you need to do is set the Form's visibility through a property:

    Application.Run(new MyForm() { Visible = false });
    

    Just make sure you remove the call to Close() in the constructor, or even move the property assignment there too.

    0 讨论(0)
提交回复
热议问题