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
15.9k18 gold badges66 silver badges80 bronze badges
asked May 1, 2011 at 11:47
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 PassantHans Passant
924k146 gold badges1697 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
2,3287 gold badges49 silver badges90 bronze badges
answered Nov 18, 2016 at 12:09
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 can I seal a crack in a teapot in a foodsafe manner?
-
Can a graph problem remain NP-hard when restricted to cycle graphs?
-
What’s the role of the pronoun «iis» in this context?
-
outlook.office.com — 500 Something went wrong. Repeating redirects detected
-
Who coined the term «signal-to-noise ratio» and when did statisticians start using the term «noise» to describe randomness?
-
Does nature jump?
-
Why do Atlas III and V use Russian RD-180 engines?
-
Is there a reasonable explanation for why my professor submitted my recommendation letter months early?
-
mv a bunch of files, but ask for each file
-
Idiom for unexpected solution?
-
Old military sci fi book about a spaceship on the edge of disaster
-
Do ORCA input files allow for multi-line comments or different comment syntaxes?
-
Interactive papers
-
Is there a quick way of changing the % Resolution in Output Properties?
-
First direct conflict within Israel’s boundaries since the 1948 Arab–Israeli War?
-
What is Earth’s apparent magnitude from geosynchronous orbit?
-
How to stop Steam trying to read from a non-existent drive?
-
Schengen to Schengen with connecting flight via UK (non-Schengen)
-
Running out of time in a world where time has stopped, how to make it consistent?
-
What happened to my car
-
How does this voltage doubler obtain a higher voltage output than the input of 5 V?
-
Example for distributions that are not normal but have equal mean
-
How long do modern flush toilets last?
-
How to get a partition from an irrep of Sn
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.
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
15.9k18 gold badges66 silver badges80 bronze badges
asked May 1, 2011 at 11:47
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 PassantHans Passant
924k146 gold badges1697 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
2,3287 gold badges49 silver badges90 bronze badges
answered Nov 18, 2016 at 12:09
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
-
What to do when advanced undergraduate and/or early graduate STEM students cannot perform correct math manipulations?
-
Why are jurors asked if each element of a crime is proved, rather than the crime as a whole
-
What makes some players so good?
-
PIC based MCU coding to make a speedometer
-
Better code for Ramsey partitions
-
When did “word” become a synonym of “promise” for the first time?
-
The slang term for books made of paper
-
First direct conflict within Israel’s boundaries since the 1948 Arab–Israeli War?
-
When/How to use reserve fuel tank in crafstman rider mower?
-
Is 14.29 volts too strong for a 14V DC chronograph?
-
Is it legal to sign a “contract” like that of Colleen Stan to voluntarily bond oneself into slavery?
-
Does being in the Shadowfell (5E) in any way affect spells that players cast?
-
What’s the role of the pronoun «iis» in this context?
-
What do the notes represent if their relationships are different in different tuning systems?
-
Can a country learn I have two passports from another country?
-
Old military sci fi book about a spaceship on the edge of disaster
-
Old story about slow light
-
Do the military really use GA planes as target practice?
-
Wall too thin for outlet box?
-
Why do Atlas III and V use Russian RD-180 engines?
-
Do published research papers cite preprints?
-
Who coined the term «signal-to-noise ratio» and when did statisticians start using the term «noise» to describe randomness?
-
Why are jurors still asked to operate the law if their primary role is to find facts?
-
How can I seal a crack in a teapot in a foodsafe manner?
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.
koc94ok 13 / 13 / 2 Регистрация: 22.04.2010 Сообщений: 642 |
||||
1 |
||||
Переход между формами14.10.2010, 18:32. Показов 136683. Ответов 30 Метки нет (Все метки)
Нажатием на клавишу закрыть текущую форму(Form1) и открыть новую(Form2)
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
14.10.2010, 18:32 |
Ответы с готовыми решениями: Переход между формами Правильный переход между формами Обычный переход между формами Переход между двумя формами 30 |
free6878 9 / 9 / 1 Регистрация: 01.09.2010 Сообщений: 182 |
||||
14.10.2010, 18:53 |
2 |
|||
Вот как-то так!?
2 |
koc94ok 13 / 13 / 2 Регистрация: 22.04.2010 Сообщений: 642 |
||||
14.10.2010, 19:43 [ТС] |
3 |
|||
Вот как-то так!? вторая форма появляется и тут же закрывается, нет не так к сожалению
0 |
CEO 2258 / 1248 / 57 Регистрация: 16.03.2009 Сообщений: 3,588 |
|
14.10.2010, 20:41 |
4 |
вторая форма появляется и тут же закрывается, нет не так к сожалению это потому что у вас первая форма является главной в приложении — при ее закрытии программа завершается. Чтоб скрыть можно вызвать метод Hide(), только потом не забудьте убить форму
1 |
13 / 13 / 2 Регистрация: 22.04.2010 Сообщений: 642 |
|
14.10.2010, 20:52 [ТС] |
5 |
это потому что у вас первая форма является главной в приложении — при ее закрытии программа завершается. Чтоб скрыть можно вызвать метод Hide(), только потом не забудьте убить форму А если в program.cs похимичить? Условие какое-либо добавить(или цикл пока) чтобы только при выполнении него первая форма закрылась и открылась вторая? зы как убить первую форму?
0 |
CEO 2258 / 1248 / 57 Регистрация: 16.03.2009 Сообщений: 3,588 |
|
14.10.2010, 21:00 |
6 |
А если в program.cs похимичить? Не стоит
Условие какое-либо добавить(или цикл пока) чтобы только при выполнении него первая форма закрыталась и открылась вторая? думаю плохо будет
зы как убить первую форму? передаем ссылку на нее во вторую форму и вызвываем form1.Close() при закрытии второй формы (или последней сторонней формы)
0 |
13 / 13 / 2 Регистрация: 22.04.2010 Сообщений: 642 |
|
14.10.2010, 21:05 [ТС] |
7 |
Не стоит думаю плохо будет передаем ссылку на нее во вторую форму и вызвываем form1.Close() при закрытии второй формы (или последней сторонней формы) ясно, а как ссылку передать?
0 |
CEO 2258 / 1248 / 57 Регистрация: 16.03.2009 Сообщений: 3,588 |
|
14.10.2010, 21:32 |
8 |
0 |
koc94ok 13 / 13 / 2 Регистрация: 22.04.2010 Сообщений: 642 |
||||||||
14.10.2010, 23:04 [ТС] |
9 |
|||||||
делаю так:
и так
результат — ошибка…
0 |
Alligieri CEO 2258 / 1248 / 57 Регистрация: 16.03.2009 Сообщений: 3,588 |
||||
15.10.2010, 01:16 |
10 |
|||
koc94ok, ну у меня слов нет
Добавлено через 54 секунды
1 |
koc94ok 13 / 13 / 2 Регистрация: 22.04.2010 Сообщений: 642 |
||||
15.10.2010, 08:34 [ТС] |
11 |
|||
Нашел в инете еще такой способ:
Вроде тоже работает
3 |
CEO 2258 / 1248 / 57 Регистрация: 16.03.2009 Сообщений: 3,588 |
|
15.10.2010, 10:20 |
12 |
koc94ok, ну при ShowDialog() — да, поскольку цикл обработки не выходит за пределы Form2 пока она не закрыта
0 |
13 / 13 / 2 Регистрация: 22.04.2010 Сообщений: 642 |
|
15.10.2010, 10:42 [ТС] |
13 |
Мммм, а как передать CookieContainer скажем?
0 |
CEO 2258 / 1248 / 57 Регистрация: 16.03.2009 Сообщений: 3,588 |
|
15.10.2010, 11:04 |
14 |
koc94ok, вы явно не читаете те ссылки что я вам даю
0 |
koc94ok 13 / 13 / 2 Регистрация: 22.04.2010 Сообщений: 642 |
||||||||
15.10.2010, 11:13 [ТС] |
15 |
|||||||
koc94ok, вы явно не читаете те ссылки что я вам даю читал и делал как там сказано
form1
ошибки почти везде
0 |
CEO 2258 / 1248 / 57 Регистрация: 16.03.2009 Сообщений: 3,588 |
|
15.10.2010, 11:43 |
16 |
public Form2(Form1 f1, string data) сколько принимает параметров? а тут —
Form2 f = new Form2(this.cooookies); ?
0 |
koc94ok 13 / 13 / 2 Регистрация: 22.04.2010 Сообщений: 642 |
||||||||
15.10.2010, 12:07 [ТС] |
17 |
|||||||
форм1:
форм2:
осталась одна ошибка:
0 |
CEO 2258 / 1248 / 57 Регистрация: 16.03.2009 Сообщений: 3,588 |
|
15.10.2010, 12:13 |
18 |
this.nnc не обьявлен в зоне видимости данного кода, определите как приватное поле
0 |
koc94ok 13 / 13 / 2 Регистрация: 22.04.2010 Сообщений: 642 |
||||
15.10.2010, 12:18 [ТС] |
19 |
|||
не обьявлен в зоне видимости данного кода, определите как приватное поле это как?
0 |
Alligieri CEO 2258 / 1248 / 57 Регистрация: 16.03.2009 Сообщений: 3,588 |
||||
15.10.2010, 12:57 |
20 |
|||
koc94ok, так он есть локальной переменной и извне не видим. надо:
обьявить
1 |
- Remove From My Forums
Переходы между формами
-
Вопрос
-
Всем привет. Возникла такая проблема.
Есть две формы, необходимо сделать так, чтобы по клику на кнопку на первой форме — появлялась вторая, а первая скрывалась. А по клику на кнопку на второй форме — вторая закрывалась, а первая появлялась.
Пробовал делать несколькими вариантами:
Первый вариант:
//кнопка на первой форме 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 10 forms and each form has Next and Previous buttons. What is the best approach to show and close forms. I don’t need forms to stay in memory.
Any ideas?
asked Jan 12, 2012 at 17:35
7
I would make use of something similar to a FormSwitcher:
public class FormSwitcher
{
private List<Func<Form>> constructors;
private int currentConstructor = 1;
public FormSwitcher(Func<Form> firstForm)
{
constructors = new List<Func<Form>>();
AddForm(firstForm);
}
public void AddForm(Func<Form> constructor)
{
constructors.Add(constructor);
}
public Form GetNextForm()
{
if (constructors.Count > 0 && currentConstructor >= constructors.Count)
{
currentConstructor = 0;
}
if (constructors.Count > currentConstructor)
{
return constructors[currentConstructor++]();
}
return null;
}
}
Your main form should look like this:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
new FirstForm().Show();
}
}
The rotating forms could look like this:
public partial class FirstForm : Form
{
private FormSwitcher switcher;
public FirstForm()
{
InitializeComponent();
switcher = new FormSwitcher(() => new FirstForm());
switcher.AddForm(() => new SecondForm(switcher));
switcher.AddForm(() => new ThirdForm(switcher));
}
private void button1_Click(object sender, EventArgs e)
{
switcher.GetNextForm().Show();
Close();
}
}
public partial class SecondForm : Form
{
private FormSwitcher switcher;
public SecondForm(FormSwitcher switcher)
{
InitializeComponent();
this.switcher = switcher;
}
private void button1_Click(object sender, EventArgs e)
{
switcher.GetNextForm().Show();
Close();
}
}
public partial class ThirdForm : Form
{
private FormSwitcher switcher;
public ThirdForm(FormSwitcher switcher)
{
InitializeComponent();
this.switcher = switcher;
}
private void button1_Click(object sender, EventArgs e)
{
switcher.GetNextForm().Show();
Close();
}
}
answered Jan 12, 2012 at 17:55
2
Don’t do it.
Have one form, ten user controls, perferably ones that implement an interface.
Take as much of the code out of the forms as you can, all is good…
Hit the abstract button now, otherwise next version in you’ll be having form 3 check form 1 to see if you can skip form 2 when going back in edge case scenario 634, while rembering if you do go forwrds from 1 you can skip 2 as well, unless they ticked box 14 and put a «Fred» in box 8.
This is not a teeshirt you want to wear.
answered Jan 12, 2012 at 18:31
Tony HopkinsonTony Hopkinson
20.2k3 gold badges32 silver badges39 bronze badges
I would use a separate reference for each window which you can set to null in case you don’t need it any more. When there’s no reference any more that points to an object the garbage collector will call it’s destructor after some time.
If I got it right you have a number of windows, say n windows, that do their job for some time and are then not needed any more. So when you write
Window myWindow_1 = new Windowd ();
Window myWindow_2 = new Windowd ();
Window myWindow_3 = new Windowd ();
// ...
Window myWindow_n = new Windowd ();
And if you want them to leave the memory you can simply do
myWindow1 = null;
myWindow2 = null;
myWindow3 = null;
//...
myWindow4 = null;
In case these are the only references that were used to link to the Window-objects they will remain as un-referencable ghosts in memory and the garbage collector will remove them after some time.
For simplicity you can hold all these references in an array to avoid giving each object a name. For exapmle:
Window[] myWindows = new Window[n];
for (int i=0; i<n; i++) {
myWindows[i] = new Window();
}
Hope this helps
answered Jan 12, 2012 at 17:45
marc wellmanmarc wellman
5,8285 gold badges33 silver badges59 bronze badges
0