Windows forms перейти на другую форму

Asked

Viewed
22k times

I’m using winforms now.
I have the main form «form1» and I have a button that opens form2.
When I open form2 I would like for form1 to disappear. When the user click the x button on form2 I would like for it to close and go back to form1. I wouldn’t like to use modal windows.

  • winforms

Corey Adler's user avatar

Corey Adler

15.9k18 gold badges66 silver badges80 bronze badges

asked May 1, 2011 at 11:47

Itay.B's user avatar

Itay.BItay.B

4,00114 gold badges62 silver badges96 bronze badges

2 Answers

    private void button1_Click(object sender, EventArgs e) {
        var frm = new Form2();
        frm.Location = this.Location;
        frm.StartPosition = FormStartPosition.Manual;
        frm.FormClosing += delegate { this.Show(); };
        frm.Show();
        this.Hide();
    }

answered May 1, 2011 at 11:56

Hans Passant's user avatar

Hans PassantHans Passant

924k146 gold badges1696 silver badges2536 bronze badges

1

  • Nice one, I was using owner property up till this point but this would do it and actually much easier.

    Jan 30, 2012 at 1:17

In order not to change Form’s Properties, simply use the ShowDialog() method in Form1.cs code to open Form2. That will deactivate Form1:

void OpenSecondForm()
{
  Form form2 = new Form();
  form2.ShowDialog();
}

KernelPanic's user avatar

KernelPanic

2,3287 gold badges49 silver badges90 bronze badges

answered Nov 18, 2016 at 12:09

YuriArtem's user avatar

2

  • I think there is a typo. sb Form form2 = new form2();

    Aug 5, 2021 at 23:58

  • Pat is right, so anyone using this example should bear that in mind.

    Jun 19 at 14:41

  • The Overflow Blog
  • Featured on Meta

Linked

Related

Hot Network Questions

  • When did “word” become a synonym of “promise” for the first time?

  • How can I tap a M5 hole in hardened steel bearing?

  • Why are these SATA bus ports different?

  • Use of the word «грамота»

  • Is 14.29 volts too strong for a 14V DC chronograph?

  • Meaning of «schon einmal»

  • For binary stars, what is the average semi-major axis?

  • Colouring a rug

  • Spacing on text macros

  • Difference between KDE, MLE and EM for density estimation

  • Copy contents of one file to another using sed

  • What do to with this vent?

  • Who coined the term «signal-to-noise ratio» and when did statisticians start using the term «noise» to describe randomness?

  • Can a social sciences doctoral thesis be just 65k words long?

  • How do Landau and Lifshitz avoid the ergodicity problem?

  • Concrete representation of coend in linear algebra

  • A 70s short story about fears made real

  • How to manually verify an ECDSA signature in Python?

  • What could happen if my university loses its R2 status?

  • Why is the central truss segment of the ISS called S0?

  • Does general linear model includes interaction?

  • How to know the sample arithmetic mean and standard deviation if I know the mean and the deviation of the logarithm of the observations

  • What do the notes represent if their relationships are different in different tuning systems?

  • Is every character of the algebra of continuous functions on a locally compact space some evaluation?

more hot questions

Question feed

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Помогаю со студенческими работами здесь

Переход от одной формы к другой
Как сделать переход от одной формы к другой C#?
Переход как бы есть!
он очень медленный ,можно…

Переход от одной формы к другой
Здравствуйте.
Проблема стандартна — перейти из одной формы form1 во вторую form2
При этом, не…

Плавный переход от одной формы к другой
Можно ли как то сделать плавный переход от одной формы к другой?
А то быстрый переход прямо режет…

Информация с одной формы на другую
Столкнулся с такой проблемой, что нужно со второстепенной формы вывести число на главную(Число это…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

Asked

Viewed
22k times

I’m using winforms now.
I have the main form «form1» and I have a button that opens form2.
When I open form2 I would like for form1 to disappear. When the user click the x button on form2 I would like for it to close and go back to form1. I wouldn’t like to use modal windows.

  • winforms

Corey Adler's user avatar

Corey Adler

15.9k18 gold badges66 silver badges80 bronze badges

asked May 1, 2011 at 11:47

Itay.B's user avatar

Itay.BItay.B

4,00114 gold badges62 silver badges96 bronze badges

2 Answers

    private void button1_Click(object sender, EventArgs e) {
        var frm = new Form2();
        frm.Location = this.Location;
        frm.StartPosition = FormStartPosition.Manual;
        frm.FormClosing += delegate { this.Show(); };
        frm.Show();
        this.Hide();
    }

answered May 1, 2011 at 11:56

Hans Passant's user avatar

Hans PassantHans Passant

924k146 gold badges1696 silver badges2536 bronze badges

1

  • Nice one, I was using owner property up till this point but this would do it and actually much easier.

    Jan 30, 2012 at 1:17

In order not to change Form’s Properties, simply use the ShowDialog() method in Form1.cs code to open Form2. That will deactivate Form1:

void OpenSecondForm()
{
  Form form2 = new Form();
  form2.ShowDialog();
}

KernelPanic's user avatar

KernelPanic

2,3287 gold badges49 silver badges90 bronze badges

answered Nov 18, 2016 at 12:09

YuriArtem's user avatar

2

  • I think there is a typo. sb Form form2 = new form2();

    Aug 5, 2021 at 23:58

  • Pat is right, so anyone using this example should bear that in mind.

    Jun 19 at 14:41

  • The Overflow Blog
  • Featured on Meta

Linked

Related

Hot Network Questions

  • How to know the sample arithmetic mean and standard deviation if I know the mean and the deviation of the logarithm of the observations

  • Typical and minimum ground-pedal clearance

  • Why are jurors still asked to operate the law if their primary role is to find facts?

  • Why would employee be paid less than contractor?

  • Can I switch between my two passports from the same country?

  • Copying files to directories according the file name

  • Open pdf from a commadn line and go back to the command line

  • he used to smoke with me

  • How can I seal a crack in a teapot in a foodsafe manner?

  • Is 14.29 volts too strong for a 14V DC chronograph?

  • How to do AssociationThread recursively?

  • Exact positioning and how easy would it be to recreate this in LaTeX?

  • 以后我少的一点儿 what does this mean?

  • Copy contents of one file to another using sed

  • How can unrelated language families exist?

  • Beacon contract contructor seems to call address 0x02?

  • Meaning of «schon einmal»

  • Movie involving a crashed/landed alien craft in an icy cavern

  • When did “word” become a synonym of “promise” for the first time?

  • What is Hamas’ strategy in attacking Israel?

  • A Trivial Pursuit #18 (Sports and Leisure 3/4): Connected

  • How to stabilize a sign on a dowel in a pot?

  • How to draw the trajectory of the circumscribed rectangle of an ellipse and determine the area range of the rectangle?

  • Counting in an anacrucis

more hot questions

Question feed

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

  • Remove From My Forums

 locked

Переходы между формами

  • Вопрос

  • Всем привет. Возникла такая проблема.

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

    Пробовал делать несколькими вариантами:

    Первый вариант:

    //кнопка на первой форме 
    private void button1_Click(object sender, EventArgs e)
            {
                Form f3 = new Form3();
               
                 f3.Show();
               button1.Enabled = false;
               this.Visible = false;
                
                
            }
    //евент, когда форма становится активной, чтоб визибл был тру
      private void Form2_Activated(object sender, EventArgs e)
            {
                this.Visible = true;
            }
    
    //кнопка на второй форме
     private void button2_Click(object sender, EventArgs e)
            {
                Form2 f2 = new Form2();
                f2.Activate();
                this.Close();
            }

    Данный вариант не работает — первая форма не выходит из состояния невидимости.

    Вот второй вариант:

    // кнопка на первой форме 
    Form f3 = new Form3();
               
                 f3.Show();
               button1.Enabled = false;
               this.Hide();
    //кнопка на второй форме
      private void button2_Click(object sender, EventArgs e)
            {
                Form2 f2 = new Form2();
                f2.Show();
                this.Close();
            }

    Этот вариант работает, но неверно. Почему-то на команду 

     f2.Show();

    Создаётся новый экземпляр Form2. А Form2 — главная форма приложения и в данном случае закрывая заново созданную форму 2  — приложение не закрывается, т.е. изначально созданная Form2 висит в невидимости.

    Извиняюсь за несколько путанное объяснение=) Помогите пожалуйста исправить ошибку.

Ответы

  • Вот рабочий вариант.

    //Form1.cs
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
      public partial class Form1 : Form
      {
        private Form2 form2;
        public Form1()
        {
          InitializeComponent();
          form2 = new Form2(this) { Visible = false };
    
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
          this.Visible = false;
          form2.Visible = true;
        }
      }
    }

    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
      public partial class Form2 : Form
      {
        private Form1 _form1;
        public Form2(Form1 form1)
        {
          _form1 = form1;
          InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
          this.Visible = false;
          _form1.Visible = true;
        }
      }
    }

    Т.е. в проекте создаёте две формы, причём первая будет главной, а вторая второстепенной. При инициализации первой формы(т.е при запуске приложения) создаёте экземпляр второй формы, скрываете её и добавляете туда ссылку на текущую(т.е) первую форму. А потом
    при клике скрываете первую показываете вторую, показываете первую скрываете вторую в другом обработчике(второй формы).

    • Помечено в качестве ответа

      10 марта 2012 г. 5:28

I have some code here:

private void button1_Click(object sender, EventArgs e)
{
    Application.Run(new Form3());
}

Although I don’t think this is how you are meant to change forms, when I ran it, it threw an error stating:

Starting a second message loop on a
single thread is not a valid operation

H H's user avatar

H H

264k31 gold badges332 silver badges515 bronze badges

asked Jun 15, 2011 at 21:14

Dennis's user avatar

2

You cannot use Application.Run — that is for starting windows form application (internal message loop which is shared among all forms in the application), not for showing a form. Each form has Show and Hide method so you should simply call:

private void button1_Click(object sender, EventArgs e)
{
    Form3 f = new Form3(); // This is bad
    f.Show();
}

But you should not create form each time you want to show it. If you want to have only one instance of the form you should keep it as global and only show or hide it on demand. Otherwise you will have to call Close instead of Hide to clear all resources the form consumes.

answered Jun 15, 2011 at 21:20

Ladislav Mrnka's user avatar

Ladislav MrnkaLadislav Mrnka

361k59 gold badges660 silver badges670 bronze badges

you can do as simple as it is :

test mp = new test();
mp.Text = " Welcome Mr." + textBox1.Text;
this.Hide();
mp.ShowDialog();
this.Close();

where test is your new form
and then if you wona pass variables to the other form just make you variable as public then you can make :

 mp.Text = " Welcome Mr." + textBox1.Text;

then showdialog to show your new form and close the old form..

natiiix's user avatar

natiiix

1,0151 gold badge14 silver badges21 bronze badges

answered Jun 15, 2011 at 21:21

Tamer's user avatar

TamerTamer

841 silver badge8 bronze badges

Your first form should create the second form on the first usage and hide itself from view. Then the second form will hide itself and show the first form when you switch back. Something like this…

  private Form _firstForm;
  private Form _secondForm;

  private void switchToSecond_Click(object sender, EventArgs e)
  {    
      if (_secondForm == null)
          _secondForm = new SecondForm();

      Hide();
      _secondForm.Show();
  }

  private void switchToFirst_Click(object sender, EventArgs e)
  {    
      Hide();
      _firstForm.Show();
  }

You would assign to firstForm the this value inside the constructor of the first form class and because this is the main form it will always be created at application startup. If you want to save resources you could also dispose of the second form when you switch back to the first and so recreate it each time you switch.

answered Jun 16, 2011 at 5:19

Phil Wright's user avatar

Phil WrightPhil Wright

22.6k14 gold badges84 silver badges137 bronze badges

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

Menu menu = new Menu(); // Create new instance of the new form.

menu.Show(); // Show it

Andrew's user avatar

Andrew

2,22216 silver badges15 bronze badges

answered Jan 9, 2018 at 0:52

Stephan Kazcoskvski's user avatar

Assume you have Form1 and Form2
Your scope is not clear if you want

  1. Switch between Form1 and Form2 and keep both of them alive.

  2. Keep only either Form1 or Form2 at a time.

for case 1 simple Form1.Hide() and Form2.Show() would be adequate.

for case 2 the solution will be a little bit complicated.

  1. Create your own instance of ApplicationContext MyAppCxt= new ApplicationContext().
  2. instead of the default Program.Run(Form1) call Program.Run(MyAppCxt(Form1))
  3. in the handler of some event, when you need to switch the Form1 and Form2

    Form2 f2 = new Form2();//Create the new form
    MyAppCxt.MainForm = f2;//set Form2 as MainForm in the message queue
    Form2.Close()//Close Form2 and release all the resource
    F2.Show();//display Form2 to the user

the same scenario would be repeated when required to switch back between Form2 and Form1

answered Apr 4, 2019 at 10:34

Ahmed Bahtity's user avatar

  • Windows git could not read from remote repository git
  • Windows future experience pack что это
  • Windows forms c visual studio 2017
  • Windows forms панель элементов пустая
  • Windows forms c open file