opening a window form from another form programmatically

后端 未结 6 1360
一整个雨季
一整个雨季 2021-01-01 12:03

I am making a Windows Forms application. I have a form. I want to open a new form at run time from the original form on a button click. And then close this

6条回答
  •  抹茶落季
    2021-01-01 12:22

    This is an old question, but answering for gathering knowledge. We have an original form with a button to show the new form.

    The code for the button click is below

    private void button1_Click(object sender, EventArgs e)
    {
        New_Form new_Form = new New_Form();
        new_Form.Show();
    }
    

    Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer

    this.Load += new System.EventHandler(this.OnPageLoad);
    

    This OnPageLoad function runs when that form is loaded

    In NewForm.cs ,

    public partial class New_Form : Form
    {
        private Timer formClosingTimer;
    
        private void OnPageLoad(object sender, EventArgs e)
        {
            formClosingTimer = new Timer();  // Creating a new timer 
            formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
            formClosingTimer.Interval = 2000; // Time Interval in miliseconds
            formClosingTimer.Start(); // Starting a timer
        }
        private void CloseForm(object sender, EventArgs e)
        {
            formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
            this.Close(); // Closing the current form
        }
    }
    

    In this new form , a timer is used to invoke a method which closes that form.

    Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.

    For your knowledge,

    form.close() will free the memory and we can never interact with that form again form.hide() will just hide the form, where the code part can still run

    For more details about timer refer this link, https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2

提交回复
热议问题