Adding Form Closing Event In Code To Specific Object Instance? - c#

Pretty simple what I want to do, just want to be able to run some code after a form is closed.
Form1 f = new Form1();
f.Show();
f.formClosing ... <- I just want to run code from this context once this form has been closed

{
Form1 f = new Form1();
f.FormClosed += new FormClosedEventHandler(f_FormClosed);
f.Show();
}
void f_FormClosed(object sender, FormClosedEventArgs e)
{
// Do stuff here
}

You can handle the Form.FormClosing event.
this.FormClosing += new FormClosingEventHandler(myForm_FormClosing);
void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
//your code here
}

Form.FormClosing occurs before the form is closed. If you cancel this event, the form remains opened.
The right event to handle is Form.FormClosed :
form.FormClosed +=
new Form.FormClosedEventHandler( Place the name of the handler method here ... );

Modern inline:
FormClosed += (s, a) => { /* your code here */ };

Recently I register my FORM exit handler this way (using .NET 4.8)
public partial class Form1:Form {
public Form1() {
this.FormClosed += Form1_Closing;
}
private void Form1_Closing(object sender, EventArgs e) {
//Doing something while exit
}
}

Related

Hide Form1, show Form2 on Form1_Load

The Form1 of my App is a login page that i want to:
- show on some conditions
- hide and show Form2 on some conditions
I can hide/show a form by the button click event like so,
private void button1_Click(object sender, EventArgs e)
{
Form2 f2= new Form2();
f2.Show();
this.Hide();
}
but the same technique does not work for Form1_Load.
I have tried the first example in this thread,
Program.cs
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run();
}
Form1
private void Form1_Load(object sender, EventArgs e)
{
Form2 f2= new Form2();
f2.Show();
this.Hide();
}
but it's not showing neither Form1 or Form2, and i don't see how it could. The second example i can't understand how i can implement, and the next google results are even more confusing.
Please help i'm stuck on this for 2 hours.
In the last line in program.cs you must type new Form1() between the parenthesis. So, your program.cs code is as follow:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
C# can not hide form in form_load evant Apparently.
To resolve Hide problem, you can use of a timer and hide the form in tick event. i.e.:
Timer timer = new Timer();
private void timerTick(object sender, EventArgs e)
{
timer.Enabled = false;
this.Hide();
}
private void Form1_Load(object sender, EventArgs e)
{
timer.Tick += new EventHandler(timerTick);
timer.Interval = 10;
Form2 frm = new Form2();
frm.Show();
timer.Enabled = true;
}
This works. I tested it.
I hope this will be useful.
Hello You Can Use This
private void button1_Click(object sender, EventArgs e)
{
Form2 f2= new Form2();
if(condition==true)
{
this.Hide();
f2.ShowDialog();
this.Close();
}
}
Why don't you reverse the order of your forms? Start with the main form in the main method.
Application.Run(new Form2());
Now in the constructor of Form2 call the login form with ShowDialog and set the result of the login in a global variable inside the Form2
public class Form2:Form
{
private bool _isValidated = false;
public Form2()
{
InitializeComponent();
// Add here the conditions to check if you don't want to
// run the login process...
// if(loginNotRequired)
// _isValidated = true;
// else
using(Form1 fLogin = new Form1())
{
// This blocks until the user clicks cancel or ok buttons
DialogResult dr = fLogin.ShowDialog();
if(dr == DialogResult.OK)
_isValidated = true;
}
}
Now in the Form2.Load event check the status of your login and close the Form2 if the login is not successful
private void Form2_Load(object sender, EventArgs args)
{
if(!_isValidated)
this.Close();
else
.....
}

How can I refresh One form when the other form is closed?

I have been developing project in c#.
It has 2 form and these are connected with between each other.
I want to do that when second form is closed, first form refresh.
If I use Thread's Sleep program will be tired. I want to do this with closing events. How can I do ?(Like java's repaint)
Codes are below:
Form1
public static Form1 form;
public Form1()
{
InitializeComponent();
form = this;
}
private void button11_Click(object sender, EventArgs e)
{
Form2 yeniform = new Form2();
yeniform.Show();
}
Form2(Close Button)
private void button1_Click(object sender, EventArgs e)
{
Form1.form.Invalidate();
Form1.form.Refresh();
this.Close();
}
Bind Form_Closing event in your first form.
//Form1
private void button11_Click(object sender, EventArgs e)
{
Form2 yeniform = new Form2();
yeniform.FormClosing += new FormClosingEventHandler(this.Form2_FormClosing);
yeniform.Show();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
//Do your stuff here.
}
' button in the second form which is to be closed
' form1 is the form which is to be re loaded when form 2 is closed
private void btn_close_Click(object sender, EventArgs e)
form1.close() 'unload form 1 before closing form2
form1.show() ' form 1 reloading
unload(me) 'closing form2
end sub
This is a working sample. In parent form
private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
VendorsAddForm f = new VendorsAddForm();
f.StartPosition = FormStartPosition.CenterScreen;
f.FormClosed += new FormClosedEventHandler(child_FormClosed);
f.Show();
}
void child_FormClosed(object sender, FormClosedEventArgs e)
{
this.Refresh();
var query = dbContext.AccountObjects.Where(p => p.IsVendor == true).ToList();
accountObjectsBindingSource.DataSource = new BindingList<AccountObject>(query);
}
Note: child form is VendorsAddForm
Thank to https://www.daniweb.com/posts/jump/1302760 , I learned from there.

Run Code after Child form is closed

so I have this code
public void Update_Click(object sender, EventArgs e)
{
using (PccBiometricsHandler.Form1 ShowProgress = new PccBiometricsHandler.Form1())
{
menu.Items[2].Enabled = false;
ShowProgress.ShowDialog();
ShowProgress.FormClosed += new FormClosedEventHandler(MyForm_FormClosed);
}
}
public void MyForm_FormClosed(object sender, FormClosedEventArgs e)
{
updaterAccess();
menu.Items[2].Enabled = true;
}
so after I click Update it will run the child form Form1
which is this:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
notifyIcon1.Visible = true;
notifyIcon1.BalloonTipTitle = "Update Complete";
notifyIcon1.BalloonTipText = "Successfully Update";
notifyIcon1.ShowBalloonTip(500);
timer1.Interval = 4000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
notifyIcon1.Dispose();
this.Close();
}
so as you can see it runs on a backgroundworker with a timer to close the child Form1
now my problem is that after closing the Child Form1 it doesn't run the MyForm_FormClosed which it should enable menu.Items[2] again and updaterAccess()
I think I'm missing something in my mainForm
Attached the event handler before firing ShowDialog
public void Update_Click(object sender, EventArgs e)
{
using (PccBiometricsHandler.Form1 ShowProgress = new PccBiometricsHandler.Form1())
{
menu.Items[2].Enabled = false;
ShowProgress.FormClosed += new FormClosedEventHandler(MyForm_FormClosed); //Attached the event handler before firing ShowDialog
ShowProgress.ShowDialog();
}
}
ShowDialog synchronously shows a modal dialog, meaning it blocks until the form is closed (the following code is not run until the form is closed). Therefore, when ShowDialog returns the form is already closed.
You can attach the event handler before calling ShowDialog() as #Jade suggests, which will work, but honestly you do not need to use the event system at all. Simply wait for ShowDialog to return then perform the actions you would when the form is closed:
public void Update_Click(object sender, EventArgs e)
{
using (PccBiometricsHandler.Form1 ShowProgress = new PccBiometricsHandler.Form1())
{
menu.Items[2].Enabled = false;
ShowProgress.ShowDialog();
}
updaterAccess();
menu.Items[2].Enabled = true;
}
If you want to do this in VB:
AddHandler ShowProgress.FormClosed, AddressOf MyForm_FormClosed

How can I ensure only a single instance of a Form will be opened?

On button click, I open a new form (lets say Form2), but I don't want that Form2 to open more than 1time. And I don't want to use .ShowDialog(), because it wont allow me to go to the Previous Form. How can I do that ?
You can use Application.OpenForms property to check if form already opened:
if (!Application.OpenForms.OfType<Form2>().Any())
{
Form2 form2 = new Form2();
form2.Show();
}
You can show existing form instead of creating new:
Form2 _form2 = null;
void Button1_Click(object sender, EventArgs e)
{
if (_form2 == null)
{
_form2 = new Form2();
_form2.Closed += Form2_Closed;
}
_form2.Show();
_form2.BringToFront();
}
private void Form2_Closed(object sender, System.EventArgs e)
{
_form2 = null;
}
You can issue the Show method, which will show the form and allow the users to get back to the form, but then you can also override the OnClosing event of the form:
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
}
and that will keep the users from being able to literally close the form. Finally, if you wanted, you could Hide the form when the user closes it:
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
this.Hide();
}
and then you'll need to hold on to that instance in the first form so that you can re-show it when the button is clicked. So in the first form you might have a class field like this:
private Form2 _form2 = new Form2();
and then in the button click it would look like this:
_form2.Show();
and since they can't actually close the form this will always work.
You can try something like
bool windowIsNotOpen;
Mutex mutext = new Mutex(true, "Form2", out windowIsNotOpen);
if (!windowIsNotOpen)
{
// Form2 is already open
return;
}
You can do a static property that tells you whether it's open or not. You'd set it when the form is opened, and turn it off when the form is closed.
class Form2 {
public static bool IsOpen { get;set; }
public Form2() {
Load += (sender, e) => { Form2.IsOpen = true; };
Closed += (sender, e) => { Form2.IsOpen = false; };
}
}
Whenever you want to open it, check the flag first.
Form2 f;
bool isOpen = false;
private void button1_Click(object sender, EventArgs e)
{
if (f == null)
{
f = new Form2(); ;
f.FormClosed += new FormClosedEventHandler(f_FormClosed);
}
if (!isOpen)
{
isOpen = true;
f.Show();
}
}
void f_FormClosed(object sender, FormClosedEventArgs e)
{
isOpen = false;
}
Try this or use Application.OpenForms and check which one opened

Automatically hide one form in C# after many second and show another form

I need to hide current form after many second and then show any form
I'm writing this code but it doesn't work.
namespace tempprj
{
public partial class ProfileFrm : Telerik.WinControls.UI.RadForm
{
public ProfileFrm()
{
InitializeComponent();
}
private void ProfileFrm_Load(object sender, EventArgs e)
{
Frm2 child = new Frm2();
Thread.Sleep(3000);
this.Hide();
child.ShowDialog();
}
}
}
Thread.Sleep(3000);
is going to prevent your project from doing anything at all for 3 seconds (not counting other threads) and freeze the UI. I suggest using the standard .NET timer.
http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx
This is a solution to my question:
private void ProfileFrm_Load(object sender, EventArgs e)
{
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Enabled = true;
timer1.Interval = 4000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
this.Hide();
Frm2 f = new Frm2();
f.ShowDialog();
}

Categories

Resources