How to press a button from another form using C#? - c#

I have 2 forms:
Form1 that make a screenshot.
Form2 that have 2 buttons to manipulate the screenshot created by form1.
Form1 also have a "hidden" button that contain the method to save the screenshot.
My questions:
How can i click the form1's button from form2?
and
How can i check when the form1 is closed and then close form2 too?
I've tried something like this but nothing happens when i click form2 save button:
var form = Form.ActiveForm as Form1;
if (form != null)
{
form.button1.PerformClick();
}

First of all the normal way multiple forms work is that when you close down the Startup form then the secondary forms will close also. If you are creating your Form2 in Form1 I would show it by using (your second Forms Instance).Show(this). You could then access the Form by Form2's Parent Property. i.e.
var form = (Form1)this.Owner();
You should then be able to access all of the public methods of Form1, Also I would take the code that you are using to save your screenshot and put into a public method, no need to have it in a Button's click event especially if the button is hidden.
Here is a quick example:
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Show(this);
}
}
Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var frm = (Form1)this.Owner;
if (frm != null)
frm.button1.PerformClick();
}
}

Instead of making a hidden button just make a method not linked to a button.
In Form1.cs:
public void SaveScreenshot()
{
//TODO: Save the Screenshot
}
In Form2.cs:
Form1 form = Application.OpenForms.OfType<Form1>().FirstOrDefault();
if (form != null) {
form.SaveScreenshot();
}
Also make sure to declare the SaveScreenshot method as public or internal.
I changed the code that gets Form1. If you click a button on Form2 then Form2 will be the ActiveForm, so your code will never "see" Form1. I used LINQ methods in my code that will only work if you have a using System.Linq; at the top of your code.

Related

how to hide form1 by clicking button in form2

I designed a form for login that named as form1, and have 2 more form form2,form3
form2 items showing in panel from form1
and what I want to do
when I click the button in panel ( the item from form2 ) want to show form2 and hide form1 but the code isnt working
private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
Form3 frm3 = new Form3();
frm1.Hide();
frm3.Show();
};
form3 is opening but form1 isnt hiding
Its not hiding because you created a new instance for form1 which is already instantiated.
You must call the Hide() method on the same instance used to call the Show() method.
If you added this code inside form1 class ,then change it like this
private Form1 frm1
public Form2()
{
frm1 = new Form1()
}
private void button_show_form1_Click(object sender, EventArgs e)
{
frm1.Show();
};
private void button1_Click(object sender, EventArgs e)
{
Form3 frm3 = new Form3();
frm3.Show();
frm1.Hide();
};
You creating both forms in your codesnipped. Form1 is not the form you want to close, i think. frm1 is only another instance of Form1, but not the openend instance von Form1. You must have anywhere another instance of Form1. You must use the right referenz to the right instance.
It is important to know that WinForms create an instance of the startup form. In our case the startup form would be Form1. So, when you say
Form1 frm1 = new Form1();
You're actually creating a new (second) instance of Form1. This means that, in code, there are two different Form1's.
What we want to do is check with our application to get the instance of Form1 that already exists.
// This goes in Form2. It returns an instance of Form1, if it exists.
private Form getForm1()
{
// Application holds information about our application, such as which forms are currently open.
var formCollection = System.Windows.Forms.Application.OpenForms;
// Now we loop through the open forms in search of the form we want, Form1.
foreach (Form frm in formCollection)
{
if (frm.Name.Equals("Form1"))
{
return frm;
}
}
return null;
}
Now that we can get the existing instance of Form1 we can use it to make the form hidden.
private void button1_Click(object sender, EventArgs e)
{
var form1 = getForm1();
if (form1 != null) form1.Hide();
}
Something to know here is that when a form is hidden it is not closed. So, we need to make sure that Form1 becomes visible again. For example, we can set Form1 to be visible when Form2 closes.
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
// The question mark (?) checks to see if the result of
// getForm1() is null. Same thing that is happening in
// button1_click
getForm1()?.Show();
}
Complete Form2 Code
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var frm1 = getForm1();
var frm3 = new Form3();
if (frm1 != null) frm1.Hide();
frm3.Show();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
// The question mark (?) checks to see if the result of getForm1() is null. Same thing that is happening in button1_click
getForm1()?.Show();
}
// This goes in Form2. It returns an instance of Form1, if it exists.
private Form getForm1()
{
// Application holds information about our application, such as which forms are currently open.
// Note that Open and Visible have different definitions.
var formCollection = System.Windows.Forms.Application.OpenForms;
// Now we loop through the open forms in search of the form we want, Form1.
foreach (Form frm in formCollection)
{
if (frm.Name.Equals("Form1"))
{
return frm;
}
}
return null;
}
}

Make the startup form visible again after hiding it

I am trying to create a two-form Windows Application in C#. For simplicity and to help me figure it out before using it elsewhere, I have essentially created a Windows form application with two forms: Form1 and Form2, Form1 showing on startup. At the click of a button, I can get Form1 to "disappear" and Form2:
private void button1_Click(object sender, EventArgs e)
{
Form2 x = new Form2();
x.Show();
this.Hide();
}
And this works great. However, when I want to return to Form1 (by making it visible again) and unload Form2, I am unsure how to proceed with coding Form2 to return the user to Form1 using a button click as well. I'm not sure what to refer to to make that form visible again, instead of having to create a new Form1 and loading it, thereby leaving my original startup form sitting in memory.
Any help you can provide would be awesome! Thanks in advance,
-Jan
As Alfie comment suggests, you need to control your instances of each form somehow.
I'd suggest a static class with two variables. When you start up you link the forms to these public properties in the static class.
something like this:
public static class App {
public static Form Form1;
public static Form Form2;
}
on startup or the click method, you'd say something like:
private void button1_Click(object sender, EventArgs e)
{
if (App.Form1 != null)
{
App.Form1 = new Form1();
}
App.Form1.Show();
App.Form2.Hide();
}
Do this:
private void button1_Click(object sender, EventArgs e)
{
Form2 x = new Form2();
this.Hide();
x.ShowModal();
this.Show();
}

A blocking/unblocking winforms call

I am currently facing this scenario and i need your help :
Having two winForms Form1 and Form2, a click button's event on form1 will launch form2.
I want to launch form2 and close (dispose) form1.
I have two ways to call form2 :
1) Using a blocking call with ShowDialog();
namespace programm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void callForm2bt_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ShowDialog();
this.Close();
}
}
}
In this case, once form2 is called i can't close (dispose) form1.
2) Using an unblocking call with Show() ;
namespace programm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void callForm2bt_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
this.Close();
}
}
}
In this case, once form1 is closed ( disposed) it dispose automatically form2.
Any idea how to dispose form1 and keeping form2 functional ?
Thanks
Either do the inverse: run the Form2 as the main form, and set its visibility to false, and start Form1 from it, and when finished from Form1 close it and set the Form2 visibility to true. So:
static void Main()
{
...
Application.Run(new Form2());//instead of Form1
}
public class Form2 ...
{
//At From2.Load:
private void Form2_Load(object sender, EventArgs e)
{
this.Hide();//the form2 will hide and show the form 1.
Form1 form1 = new Form1(this);
form1.Show();
}
}
public class Form1...
{
private Form2 _form2 = null;
public Form1()
{ InitializeComponents();}
public Form1(Form2 form2) : this()
{
_form2 = form2;
}
private void callForm2bt_Click(object sender, EventArgs e)
{
if (_form2 != null)
{
_form2.Show();
}
this.Close();
}
}
Or use your current method but don't close the Form1, instead set its visability to false when you finished from it. by calling this.Hide(); or this.Visable = false; Like:
private void callForm2bt_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
this.Hide();//this will hide the control from the user but it will still alive.
}
Edit: At the first solution you can also use form1.ShowDialog() and get rid from passing Form2 instance to Form1 constructor, So:
//At From2.Load:
private void Form2_Load(object sender, EventArgs e)
{
this.Hide();//the form2 will hide and show the form 1.
Form1 form1 = new Form1();
form1.ShowDialog();
this.Show();//the form1 is closed so just show this again.
}
From MSDN for Application.Run(Form) method:
"This method adds an event handler to the mainForm parameter for the Closed event. The event handler calls ExitThread to clean up the application."
http://msdn.microsoft.com/en-us/library/ms157902(VS.90).aspx
Basically, when your main form exits, all message pumps are stopped.
I don't know what the forms do in your real-world application but you'll have to work around this behavior. Some ideas - and the correct one probably depends on what you're doing:
If Form1 is some kind of dialog, you could call ShowDialog on it before Application.Run. For example:
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 fm = new Form1();
fm.ShowDialog();
Application.Run(new Form2());
}
When Form1 is closed then Form2 will be opened. The return value of ShowDialog could be used to determine whether to proceed and open Form2, or exit the application.
Another idea might be to call Application.Run twice. Form1 could set a flag indicating whether to open Form2.
Usually in my applications, Form1 is typically some kind of dialog (e.g. a registration form, etc.) and so the first behavior is usually what I do. If the dialog is cancelled then I don't run the application.
Edit: If Form1 may branch out to a number of other forms, you could have it return the form for opening to Main via a field. For example:
Add a public field "Form FormToOpen" to Form1. Set it to null when the form is constructed.
When the button on Form1 is pressed, give FormToOpen a value. For example: "FormToOpen = new Form2()".
Change the Application.Run line as follows:
if (fm.FormToOpen != null) Application.Run(fm.FormToOpen);
At this point it would be trivial for Form1 to have more buttons that open other forms. The main function would not need special knowledge about each form, and the additional forms would not need special knowledge about Form1.
Consider injection of Form2 instance through constructor of Form1, it reduces a class coupling and increases a flexibility, in this way you can safely dispose form1 and keep form2 a live

How can I navigate between forms

I am a newbiest in c# and window form
i am doing a project and i meet some problem
how can i navigate forms within the window( i have a menu strip, when click it will show a item "Brand", so when i click it, it should open up within the window , i don't want something using the mdiparent/container, i have form1 and form2, then i put the menu strip in form1, which there is some thing inside form1, if use the mdiparent/container, the form1 content/thing will block the form2 )
2.i use the below code and the problem is i want to close the form1 which i click on " Brand" in the menu strip...but how???
public partial class Form1 : Form
{
// i put the menu strip in form1 design
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Check_Click(object sender, EventArgs e)
{
Form2 Check = new Form2();
Check.Show();
}
}
You cannot just close the Form1 as it is the main form, but you can hide it. Use this.Hide().
private void Check_Click(object sender, EventArgs e)
{
Form2 Check= new Form2();
Check.Show();
Hide();
}
[EDIT]
Not sure if this is what is asked. But...
There are many ways to implement navigation between forms, for example:
In Form1:
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Tag = this;
form2.Show(this);
Hide();
}
In Form2:
private void button1_Click(object sender, EventArgs e)
{
var form1 = (Form1)Tag;
form1.Show();
Close();
}
I think you should create usercontrols rather than different forms. Then you can add your usercontrols in your main panel according to the selection in the menu.
Initially something like below
this.panel.Controls.Clear();
this.panel.Controls.Add(new UserControl_For_Form1());
Once the user click some other selection in menu.
this.panel.Controls.Clear();
this.panel.Controls.Add(new UserControl_For_Form2());
If you really want to use the way that you are using at the moment. Below code will help.
Add a Form1 property for the Form2 and parse the form1 instance to the Form2 with its constructor.
public partial class Form2 : Form
{
private Form1 form1;
public Form2(Form1 myForm)
{
InitializeComponent();
form1 = myForm;
}
}
Show the form2 and hide the form1.
private void Check_Click(object sender, EventArgs e)
{
Form2 Check= new Form2(this);
Check.Show();
Hide();
}
In form2 closing event now you can show the form1 instance which is in the form2 and close the form2.
Using of MDI form is another option for you.
It has been 7 years since this question was asked but I wanna give an answer in case if someone is still looking for a solution. If you are using DevExpress, you can add Navigation Frame to your program. You can switch between different components such as GridControl, GroupBox and so on. So you dont have to create an extra form in order to navigate between forms.

Passing data between forms

I have two forms. First, Form1 has a group box, some labels and a listbox. I press a button and new Form2 is opened and contains some text. I want to transfer the text in Form2 to the listbox in the Form1.
So far, what I have done is make modifier of listbox to public and then put this code in the button of Form2
Form1 frm = new Form1();
frm.ListBox.items.Add(textBox.Text);
But amazingly, this does not add any value. I thought I was mistaken with the insertion so I made the same procedure. This time, I made a label public and added textbox value to its Text property but it failed.
Any ideas?
Try adding a parameter to the constructor of the second form (in your example, Form1) and passing the value that way. Once InitializeComponent() is called you can then add the parameter to the listbox as a choice.
public Form1(String customItem)
{
InitializeComponent();
this.myListBox.Items.Add(customItem);
}
// In the original form's code:
Form1 frm = new Form1(this.textBox.Text);
Let's assume Form1 calls Form2. Please look at the code:
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Show();
frm.VisibleChanged += formVisibleChanged;
}
private void formVisibleChanged(object sender, EventArgs e)
{
Form2 frm = (Form2)sender;
if (!frm.Visible)
{
this.listBox1.Items.Add(frm.ReturnText);
frm.Dispose();
}
}
}
Form2:
public partial class Form2 : Form
{
public string ReturnText { get; set; }
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.ReturnText = this.textBox1.Text;
this.Visible = false;
}
}
The answer is to declare public property on Form2 and when form gets hidden. Access the same instance and retrieve the value.
Below code working perfect on my machine.
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.listBox1.Items.Add(textBox1.Text );//ListBox1 : Modifier property made public
f1.ShowDialog();
}
Ok, If you are Calling Sequence is like, Form1->Form2 and Form2 updates the value of Form1 then you have to use ParentForm() or Delegate to update the previous form.
Form1 frm = new Form1();
frm is now a new instance of class Form1.
frm does not refer to the original instance of Form1 that was displayed to the user.
One solution is, when creating the instance of Form2, pass it a reference to your current instance of Form1.
Please avoid the concept of making any public members like you said
>>i have done is make modifier of listbox to public and then in form2 in button code<<
this is not a good practice,on the other hand the good one is in Brad Christie's Post,I hope you got it.
This code will be inside the form containing myListBox probably inside a button click handler.
Form2 frm2 = new Form2();
frm2.ShowDialog();
this.myListBox.Items.Add(frm2.myTextBox.Text);
frm2.Dispose();

Categories

Resources