Restore form from secondary form - c#

I have a form that minimizes when I open a secondary form (using a button click event). I want to be able to restore the original form when closing the secondary form. I have not been able to figure out how to restore the original. Here is the code I have (in example form)
The code from the main form:
private void BtnSecondaryForm_Click(object sender, EventArgs e)
{
// Open the secondary form.
FrmSecondaryForm fsf = new FrmSecondaryForm ();
fsf.Show();
this.WindowState = FormWindowState.Minimized;
}
Code from the secondary form:
private void FrmSecondaryForm_FormClosing(object sender, FormClosingEventArgs e)
{
// I need this code to be able to restore the main form.
}
Please don't just redirect me to someone else's similar question without explaining how I can get this to work in my application. I have looked at the other similar questions here on Stack Overflow already and don't understand how to get this to work.

You should find the form you want or restore, e.g.
using System.Linq;
...
private void FrmSecondaryForm_FormClosing(object sender, FormClosingEventArgs e)
var mainForm = Application
.OpenForms
.OfType<MainForm>()
.LastOrDefault();
if (mainForm != null) {
mainForm.WindowState = FormWindowState.Normal;
}
}

Move FormClosing event handler to primary form. This form is interested in the event anyway. I also changed event from FormClosing to FormClosed. Former can be called many times, but latter is called only once, when the form is actually closed.
private FrmSecondaryForm Fsf = null;
private void BtnSecondaryForm_Click(object sender, EventArgs e)
{
// Open the secondary form.
Fsf = new FrmSecondaryForm();
Fsf.Show();
Fsf.FormClosed += PrimaryForm_SecondaryFormClosed;
this.WindowState = FormWindowState.Minimized;
}
private void PrimaryForm_SecondaryFormClosed(object sender, FormClosedEventArgs e)
{
Fsf.FormClosed -= PrimaryForm_SecondaryFormClosed;
Fsf.Dispose();
Fsf = null;
this.WindowState = FormWindowState.Normal;
}

So you need Form2 to interact with Form1, which means that Form2 needs a reference to it.
Best is to do this during construction. But with forms, you should always keep a default no-parameter constructor, so we need to add a new one and make the original private.
//Add a new property (or field if you wish)
private Form formToMinimise { get; }
//Change this to be private
private SecondaryForm()
{
InitializeComponent();
}
//Add this new constructor as public
public SecondaryForm(Form form): this()
{
formToMinimise = form;
}
Now closing and restore original. We do a null check, just in case
private void FrmSecondaryForm_FormClosing(object sender, FormClosingEventArgs e)
{
formToMinimise?.WindowState = FormWindowState.Normal ;
}
Now you amend the creation and calling of your second form like this
private void BtnSecondaryForm_Click(object sender, EventArgs e)
{
// Create the secondary form with reference to this form
FrmSecondaryForm fsf = new FrmSecondaryForm(this);
fsf.Show();
this.WindowState = FormWindowState.Minimized;
}

Related

Close Form when not clicking on it

I want to know if there is any event when you click on the rest of the screen and not the Windows Form the Form closes. Is it because of the ShowDialog()?
My Main Form is just with a notifyIcon and when I click it I call Form1.ShowDialog();
Main.cs:
private void ShowForm1(object sender, EventArgs e)
{
form1.Left = Cursor.Position.X;
form1.Top = Screen.PrimaryScreen.WorkingArea.Bottom - form1.Height;
form1.ShowDialog();
}
Form1.cs:
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "Test";
}
You need to run the dialog box non-modally, not modally. Think about it, when you run it modally, the dialog box takes over the UI and plays games with mouse-clicks elsewhere, preventing you from running. You don't want it to be modal anyway.
I created a simple Windows form with a button that includes this handler to open a small AutoCloseDialog form I created (and populated with a few controls):
private void button1_Click(object sender, EventArgs e)
{
var dlg = new AutoCloseDialog();
dlg.Show(this); //NOTE: Show(), not ShowDialog()
}
Then, in the AutoCloseDialog form, I wired up the Deactivate event. I did it in the designer (where this code is generated):
this.Deactivate += new System.EventHandler(this.AutoCloseDialog_Deactivate);
Finally, here is the handler for the Deactivate event.
private void AutoCloseDialog_Deactivate(object sender, EventArgs e)
{
this.Close();
}
I think this does what you are asking.
Yes, you can create a similar function like this, which closes the Form if the Form lost focus (in Form1.cs)
public void Form_LostFocus(object sender, EventArgs e)
{
Close();
}
and then you add the LoseFocus EventHandler (in Form1.Designer.cs):
this.LostFocus += new EventHandler(Form_LostFocus);

Having problem to close a second windows form without closing the main form

In a c# I have two forms: Windows Form1 & Windows Form2.
When I click on a link label in Form1, the second form is shown. But when I close the second form, my first Windows form closes too.
my main form is:
namespace Windows_Forms_Basics
{
public partial class ShowLocationOnMapForm : Form
{
private string latitude;
private string longitute;
private GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();
public ShowLocationOnMapForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
watcher = new GeoCoordinateWatcher();
// Catch the StatusChanged event.
watcher.StatusChanged += Watcher_StatusChanged;
// Start the watcher.
watcher.Start();
}
private void button_ShowOnMap_Click(object sender, EventArgs e)
{
textBox_Latitude.Text = latitude;
textBox_Longtitude.Text = longitute;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<Pending>")]
private void Watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e) // Find GeoLocation of Device
{
try
{
if (e.Status == GeoPositionStatus.Ready)
{
// Display the latitude and longitude.
if (watcher.Position.Location.IsUnknown)
{
latitude = "0";
longitute = "0";
}
else
{
latitude = watcher.Position.Location.Latitude.ToString();
longitute = watcher.Position.Location.Longitude.ToString();
}
}
else
{
latitude = "0";
longitute = "0";
}
}
catch (Exception)
{
latitude = "0";
longitute = "0";
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private HelpForm form2 = new HelpForm();
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
form2.Show();
}
}
}
and my second form is:
namespace Windows_Forms_Basics
{
public partial class HelpForm : Form
{
public HelpForm()
{
InitializeComponent();
}
private void HelpForm_Load(object sender, EventArgs e)
{
}
private void button_BackToForm1_Click(object sender, EventArgs e)
{
ShowLocationOnMapForm form1 = new ShowLocationOnMapForm();
this.Hide();
form1.Show();
}
}
}
Do you have any idea how to tackle this problem?
I am guessing you may be “confusing” forms and one forms “ability” to access another form. Let’s start by taking a look at the bit of code in your initial question…
private HelpForm form2 = new HelpForm();
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
this.Hide();
form2.Show();
}
This code is called from (what appears to be) a Form named ShowLocationOnMapForm.
On this form is a LinkLabel named linkLabel_help and its LinkClicked event is wired up and is shown above.
In addition, there appears to be a “global” variable form2 that is a HelpForm object (first line in the code above), which is another form. It is unnecessary to create this “global” form variable in the ShowLocationOnMapForm. …. However, we will continue as it is not pertinent at this point.
When the user “clicks” the `LinkLabel’ the above method will fire.
On the first Line in the method…
this.Hide();
Is going to “hide” the current form ShowLocationOnMapForm … and “show” the second form (HelpForm) with the line…
form2.Show();
On the surface, this may appear correct, however, there is one problem that I am guessing you are missing. The problem is…
How are you going to “unhide” the first form ShowLocationOnMapForm?
The second form (HelpForm) is “shown”, however, it isn’t going to KNOW anything about the first form. In this situation the first form is basically LOST and you have no way of accessing it. Therefore when you attempt the line… form1.Show(); in the second form, the compiler is going to complain because its not going to know what form1 is. In this code, there is NO way to get back to the first form. It is not only hidden from the user, but from the second form’s perspective the “CODE” can’t see it either!
Your faulty solution is not only “creating” another form1 but it is also doing the same with the second form.
Given this, it appears clear, that if you want to keep access to the first form… then you are going to have to use a ShowDialog instead of Show OR pass the first form to the second form.
Since it is unclear “how” you want these forms to interact, I can only proffer two (2) ways that you can use to at least keep access to the first form.
1) Use ShowDialog instead of Show when displaying the second form. It may look like …
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
HelpForm form2 = new HelpForm();
this.Hide();
form2.ShowDialog();
this.Show();
}
In the code above, the ShowDialog is going to “STOP” code execution in the first form and will wait for the second form (form2) to close. When executed, the first form is hidden, then the second form is shown, however, unlike the Show command, the line this.Show(); will not be executed until the second form closes. I am guessing this may be what you are looking for.
2) Pass the first form to the second form giving the second form “access” to the first form.
This will require that the second form has a “constructor” that takes a ShowLocationOnMapForm object as a parameter. With this, the second form can create a “global” variable of type ShowLocationOnMapForm that “points” to the first form. The constructor may look like…
private ShowLocationOnMapForm parentForm;
public HelpForm(ShowLocationOnMapForm parent) {
InitializeComponent();
parentForm = parent;
}
In the first form, you would instantiate the second form with...
HelpForm form2 = new HelpForm(this);
With this approach, the second form will have total access to the first form. You could add the “back” button as you describe and simply execute the line…ParentForm.Show(); However, I recommend you also wire up the second forms FormClose event and show the first form, otherwise, if the user clicks the close button (top right) and doesn’t click the “back” button, then you will have LOST the first form again.
Without knowing “exactly” how you want these forms to interact it is difficult to proffer a complete solution.
There are also other ways to accomplish this, however these should work for most cases.
I hope this makes sense and helps.
I tried to solve this problem by placing a 'Back to Form1' button in Form2. Which works, and the solution is as follows:
on my Form1 I have:
private Form2 form2 = new HelpForm();
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
form2.Show();
}
and on my second form I have:
private void button_BackToForm1_Click(object sender, EventArgs e)
{
HelpForm form1 = new HelpForm();
this.Hide();
form1.Show();
}
But the problem is if I click the close button (on top right of the window) instead of the GoBack button on the second form, Form1 & Form2 both close in the same time.

c# i want add minimize button my form can't use Form1.WindowState = FormWindowState.Minimized;

i want add minimize button my form
private void button6_Click(object sender, EventArgs e)
{
Form1.WindowState = FormWindowState.Minimized;
}
this is not work
i got error
An object reference is required for the non-static field, method, or property 'System.Windows.Forms.Form.WindowState.get'
Yes, you're accessing the class definition (Form1), not the instance of your form.
Simpy use this.
private void button6_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
Only static fields and properties can be accessed in class, for everything else you need to create and/or use an instance of that class.
You need to set the value on an instance of your Form, such as the current instance that your button click event is firing in.
Use this instead:
this.WindowState = FormWindowState.Minimized;
(You technically don't need to include "this" either - depends on your preference.)
That being said, your code is actually minimizing the form, not adding a minimize button to the form, which is what your title indicates you're trying to do.
That button should show by default, unless you've made other customizations to your form that you're not including in the original question.
You can try this to show the minimize button if it's been hidden:
this.MinimizeBox = true;
private void button6_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
in button6_Click this means current form.
To add to what everyone said, if you need to minimise the form from another form, use:
...
Form1 f1=new Form1();
...
f1.Show();
...
private void button6_Click(object sender, EventArgs e)
{
this.f1.WindowState = FormWindowState.Minimized;
// 'this' is optional
}

How to call the mainwindow object from a second object created from main window in c# .net

Being a very first user in Windows Form Development I want to ask a simple question ...
I created a form(MainWindow.cs) within the solution which opens at the time of running that solution.
Latter I created a second form(SecondWindow.cs) and created a event so that it can be called from the first window by clicking a button.When the second window loded up the first window(MainWindow.cs) will be disabled.
Now I want to enable the MainWindow.cs when the second window is closed.
How to do That...
A simple solution I already have is to hide the MainWindow.cs and latter on closing the second window make a new object of first window and show it.But it is not a good way i think because there is already a object created by .net framework for first window automatically, so why we should create a new object of Mainwindow.cs .
Code Of First Window ( MainWindow.cs ) :
private void priceControllToolStripMenuItem_Click(object sender, EventArgs e)
{
SecondWindow price = new SecondWindow();
this.Enabled = false;
price.Show();
}
Code Of Second Window ( On closing SecondWindow.cs )
private void price_controll_FormClosed(object sender, FormClosedEventArgs e)
{
// what will goes here to make the MainWindow.cs to enable state
}
Use price.ShowDialog() to show second form as modal dialog. Main form will be disabled until you close second form:
private void priceControllToolStripMenuItem_Click(object sender, EventArgs e)
{
using(SecondWindow price = new SecondWindow())
price.ShowDialog();
}
You can pass the main form as an owner to the second form
private void priceControllToolStripMenuItem_Click(object sender, EventArgs e)
{
SecondWindow price = new SecondWindow() { Owner = this };
this.Enabled = false;
price.Show();
}
Then you can reference it from the second form.
private void price_controll_FormClosed(object sender, FormClosedEventArgs e)
{
Owner.Enabled = true;
}

How to handle object disposed exception was unhandled Exception in c#?

I am working in c# windows application.I have two windows from name as form1 and form2.i am calling form2 by clicking the button in form1 but i create the object for form2 in constrcutor of form1 .if i click the button first time form2 showed successfully after that i close the form2 by clicking the default close button and again click the button now i am getting object disposed exception was unhandled exception.how can avoid this?
Don't handle the exception, fix the bug in your code. The form instance is dead after the form is closed, you cannot show it again. Either write it like this:
private void button1_Click(object sender, EventArgs e) {
var frm = new Form2();
frm.Show(this);
}
Or if you want only one instance of the form to be ever visible:
Form2 theForm;
private void button1_Click(object sender, EventArgs e) {
if (theForm != null) {
theForm.WindowState = FormWindowState.Normal;
theForm.BringToFront();
}
else {
theForm = new Form2();
theForm.FormClosed += delegate { theForm = null; };
theForm.Show(this);
}
}
You are keeping a reference to the object (window here) but you are closing it. Object is disposed but is not garbage collected. Your reference here is invalid now as the object has lost its usable state.
You need to hide the form instead of close if you need to re-use it. Or create a new instance to load it again.
You can use events in order to let form1 know when form2 has been closed and clear its reference to it. Then form1 doesn't need to call form2 if it has been closed.
We do something similar here with a few of our tools that plug into third-party apps. Code sample below:
public class Form1 : Form
{
private Form2 otherForm;
private void ActivateForm2_Click(object sender, EventArgs e)
{
if (otherForm == null || otherForm.IsDisposed)
{
otherForm = new Form2();
otherForm.FormClosed += new FormClosedEventHandler(otherForm_closed);
}
otherForm.Show(this);
}
private void otherForm_Closed(object sender, FormClosedEventArgs e)
{
otherForm.Dispose();
otherForm = null;
}
}

Categories

Resources