Windows forms open new form

The problem beings with that line:

Application.Run(new Form1());
Which probably can be found in your program.cs file.

This line indicates that form1 is to handle the messages loop — in other words form1 is responsible to keep executing your application — the application will be closed when form1 is closed.

There are several ways to handle this, but all of them in one way or another will not close form1.
(Unless we change project type to something other than windows forms application)

The one I think is easiest to your situation is to create 3 forms:

  • form1 — will remain invisible and act as a manager, you can assign it to handle a tray icon if you want.

  • form2 — will have the button, which when clicked will close form2 and will open form3

  • form3 — will have the role of the other form that need to be opened.

And here is a sample code to accomplish that:
(I also added an example to close the app from 3rd form)

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1()); //set the only message pump to form1.
    }
}


public partial class Form1 : Form
{
    public static Form1 Form1Instance;

    public Form1()
    {
        //Everyone eveywhere in the app should know me as Form1.Form1Instance
        Form1Instance = this;

        //Make sure I am kept hidden
        WindowState = FormWindowState.Minimized;
        ShowInTaskbar = false;
        Visible = false;

        InitializeComponent();

        //Open a managed form - the one the user sees..
        var form2 = new Form2();
        form2.Show();
    }

}

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var form3 = new Form3(); //create an instance of form 3
        Hide();             //hide me (form2)
        form3.Show();       //show form3
        Close();            //close me (form2), since form1 is the message loop - no problem.
    }
}

public partial class Form3 : Form
{
    public Form3()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form1.Form1Instance.Close(); //the user want to exit the app - let's close form1.
    }
}

Note: working with panels or loading user-controls dynamically is more academic and preferable as industry production standards — but it seems to me you just trying to reason with how things work — for that purpose this example is better.

And now that the principles are understood let’s try it with just two forms:

  • The first form will take the role of the manager just like in the previous example but will also present the first screen — so it will not be closed just hidden.

  • The second form will take the role of showing the next screen and by clicking a button will close the application.

    public partial class Form1 : Form
    {
        public static Form1 Form1Instance;

        public Form1()
        {
            //Everyone eveywhere in the app show know me as Form1.Form1Instance
            Form1Instance = this;
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Make sure I am kept hidden
            WindowState = FormWindowState.Minimized;
            ShowInTaskbar = false;
            Visible = false;

            //Open another form 
            var form2 = new Form2
            {
                //since we open it from a minimezed window - it will not be focused unless we put it as TopMost.
                TopMost = true
            };
            form2.Show();
            //now that that it is topmost and shown - we want to set its behavior to be normal window again.
            form2.TopMost = false; 
        }
    }

    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form1.Form1Instance.Close();
        }
    }

If you alter the previous example — delete form3 from the project.

Good Luck.

Добавление форм. Взаимодействие между формами

Последнее обновление: 31.10.2015

Чтобы добавить еще одну форму в проект, нажмем на имя проекта в окне Solution Explorer (Обозреватель решений) правой кнопкой мыши и выберем
Add(Добавить)->Windows Form…

добавление новой формы

Дадим новой форме какое-нибудь имя, например, Form2.cs:

создание новой формы

Итак, у нас в проект была добавлена вторая форма. Теперь попробуем осуществить взаимодействие между двумя формами. Допустим, первая форма
по нажатию на кнопку будет вызывать вторую форму. Во-первых, добавим на первую форму Form1 кнопку и двойным щелчком по кнопке перейдем в файл кода. Итак,
мы попадем в обработчик события нажатия кнопки, который создается по умолчанию после двойного щелчка по кнопке:

private void button1_Click(object sender, EventArgs e)
{

}

Теперь добавим в него код вызова второй формы. У нас вторая форма называется Form2, поэтому сначала мы создаем объект данного класса, а потом для его
отображения на экране вызываем метод Show:

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

Теперь сделаем наоборот — чтобы вторая форма воздействовала на первую. Пока вторая форма не знает о существовании первой. Чтобы это исправить, надо
второй форме как-то передать сведения о первой форме. Для этого воспользуемся передачей ссылки на форму в конструкторе.

Итак перейдем ко второй форме и перейдем к ее коду — нажмем правой кнопкой мыши на форму и выберем View Code (Просмотр кода). Пока он пустой и
содержит только конструктор. Поскольку C# поддерживает перегрузку методов, то мы можем создать несколько методов и конструкторов с разными
параметрами и в зависимости от ситуации вызывать один из них. Итак, изменим файл кода второй формы на следующий:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HelloApp
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public Form2(Form1 f)
        {
            InitializeComponent();
            f.BackColor = Color.Yellow;
        }
    }
}

Фактически мы только добавили здесь новый конструктор public Form2(Form1 f), в котором мы получаем первую форму и устанавливаем ее фон
в желтый цвет. Теперь перейдем к коду первой формы, где мы вызывали вторую форму и изменим его на следующий:

private void button1_Click(object sender, EventArgs e)
{
	Form2 newForm = new Form2(this);
	newForm.Show();
}

Поскольку в данном случае ключевое слово this представляет ссылку на текущий объект — объект Form1, то при создании второй формы она будет получать ее (ссылку)
и через нее управлять первой формой.

Теперь после нажатия на кнопку у нас будет создана вторая форма, которая сразу изменит цвет первой формы.

Мы можем также создавать объекты и текущей формы:

private void button1_Click(object sender, EventArgs e)
{
	Form1 newForm1 = new Form1();
	newForm1.Show();
		
	Form2 newForm2 = new Form2(newForm1);
	newForm2.Show();
}

При работе с несколькими формами надо учитывать, что одна из них является главной — которая запускается первой в файле Program.cs.
Если у нас одновременно открыта куча форм, то при закрытии главной закрывается все приложение и вместе с ним все остальные формы.

Here I will explain how to open a second from using a first form in Windows Forms. Before that I will explain group boxes and picture boxes in Windows Forms.

Step 1: Login form

There is a login from when I enter a password and username and then the page goes directly to another page named form2.

Login from

Step 2: Add a new form

Now go to Solution Explorer and select your project and right-click on it and select a new Windows Forms form and provide the name for it as form2.

Add a new form

And the new form is:

new form

Step 3: Coding

Now click the submit button and write the code.

Coding

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. using System.Data.SqlClient;  
  9. namespace First_Csharp_app  
  10. {  
  11.     public partial class Form1 : Form  
  12.     {  
  13.         public Form1()  
  14.         {  
  15.             InitializeComponent();  
  16.         }  
  17.         private void button1_Click(object sender, EventArgs e)  
  18.         {  
  19.             try  
  20.             {  
  21.                 if (!(usertxt.Text == string.Empty))  
  22.                 {  
  23.                     if (!(passtxt.Text == string.Empty))  
  24.                     {  
  25.                         String str = «server=MUNESH-PC;database=windowapp;UID=sa;password=123»;  
  26.                         String query = «select * from data where username = ‘» + usertxt.Text + «‘and password = ‘» + this.passtxt.Text + «‘»;  
  27.                         SqlConnection con = new SqlConnection(str);  
  28.                         SqlCommand cmd = new SqlCommand(query, con);  
  29.                         SqlDataReader dbr;  
  30.                         con.Open();  
  31.                         dbr = cmd.ExecuteReader();  
  32.                         int count = 0;  
  33.                         while (dbr.Read())  
  34.                         {  
  35.                             count = count + 1;  
  36.                         }  
  37.                         if (count == 1)  
  38.                         {  
  39.                             this.hide();  
  40.                             Form2 f2 = new form2();   
  41.                             f2.ShowDialog();  
  42.                         }  
  43.                         else if (count > 1)  
  44.                         {  
  45.                             MessageBox.Show(«Duplicate username and password»«login page»);  
  46.                         }  
  47.                         else  
  48.                         {  
  49.                             MessageBox.Show(» username and password incorrect»«login page»);  
  50.                         }  
  51.                     }  
  52.                     else  
  53.                     {  
  54.                         MessageBox.Show(» password empty»«login page»);  
  55.                     }  
  56.                 }  
  57.                 else  
  58.                 {  
  59.                     MessageBox.Show(» username empty»«login page»);  
  60.                 }  
  61.                   
  62.             }  
  63.             catch (Exception es)  
  64.             {  
  65.                 MessageBox.Show(es.Message);  
  66.             }  
  67.         }  
  68.     }  

Step 4: Output

When you click on the submit button a new form will be opened named form2.

  1. Use the Form.Show() Method to Open a New Form Using a Button in C#
  2. Use the Form.ShowDialog() Method to Open a New Form Using a Button in C#

Open a Form Using a Button in C#

This tutorial will teach you how to access forms using buttons when developing applications in C#.

Use the Form.Show() Method to Open a New Form Using a Button in C#

It belongs to the System.Windows.Forms namespace and shows or displays a new form to the user. It only works for non-modal forms and can efficiently display, show, or control them.

Before calling this method, its Owner property must be set to owner so the new form can access this property to get information about the owning form. The new form will be visible after setting its Visible property to true.

You need to instantiate it as an object by creating a new object from the active form’s class. Use this instantiated object to call the Show() method, and you can access the new form.

Code — Form1.cs:

using System;
using System.Windows.Forms;

namespace openFormfromClickEvent
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // create an object of `Form2` form in the current form
            Form2 f2 = new Form2();

            // hide the current form
            this.Hide();

            // use the `Show()` method to access the new non-modal form
            f2.Show();
        }
    }
}

Output:

open form using form.show() method in csharp

Using a button to access another form can have multiple benefits as you can replicate a form as needed and easily and effectively modal some basic workflow of your C# applications. In Winforms, you can structure your applications by handling forms via Click events to manipulate the GUI.

Use the Form.ShowDialog() Method to Open a New Form Using a Button in C#

Similar to the Form.Show() method, It opens a new form as a model dialog box in your C# application, and every action in this dialog box is determined by its DialogResult property.

You can set the DialogResult property of the form programmatically or by assigning the enumeration value of the modal form to the DigitalResult property of a button. The Form.ShowDialog() method returns a value that can be used to determine how to process actions in the new modal form.

As a modal dialog box is set to Cancel, it forces the form to hide, unlike the non-modal forms. When a form is no longer in service or required by your C# application, the Dispose method becomes helpful because using the Close method can hide a form instead of closing it, which means it can be shown again without creating a new instance of the modal form.

This method does not specify a form of control as its parent as a currently active form becomes the owner (parent) of the dialog box or modal form. If there comes a need to specify the owner of this method, use the Form.ShowDialog(IWin32Window) version of the method, which shows the form as a modal dialog box with the specified owner.

Code — Form1.cs:

using System;
using System.Windows.Forms;

namespace openFormfromClickEvent
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // create an object of `Form2` form in the current form
            Form2 f2 = new Form2();

            // hide the current form
            this.Hide();

            // use the `ShowDialog()` method to access the new modal form
            f2.ShowDialog();
        }
    }
}

Output:

open form using form.showdialog() method in csharp

To hide an active form, use this.Hide() method and to close a form use this.Close() method in a button_Click event.

C# application developers must know about event handling to perform some actions on a form. The Form.cs [Design] of your C# project in Visual Studio contains the visual representation of your form elements, and by double-click, a design element can automatically create an event handler method that controls and respond to events generated from controls and a button clicked event is one of them.

  • Remove From My Forums
  • Question

  • Well… i want to do this: open a form and close the form that is open…
    Example:
    Form_P f = new Form_P();
    f.Show();
    this.Close();

    But, my program close.. why?

Answers

  • Hi jaomello: we have two ways for this problem:

    #1, Registering Form1.Closing event, cancel it and hide the main form

    #2, Start another thread for the second form:

    public static void ThreadProc()

    {

        Application.Run(new Form());

    }

    private void button1_Click(object sender, EventArgs e)

    {

        System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));

        t.Start();

    }

    Beat regards!

  • Windows forms net framework visual studio
  • Windows forms как добавить картинку
  • Windows form application c visual studio 2019
  • Windows forms image on button
  • Windows form app net framework