I have some problems with switching forms in my applications.
It have 2 forms:
- first: has one button for swith to second form;
- second: has timer for automatical switching to first form and button for manual switch to first form.
If I click button, Application executes method logOut and it works.
If it executes with events of timer – it doesn’t work. I need help to understand why it doesn’t work in this way?
Code for first form
using System;
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 frmm2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
frmm2 = new Form2(this);
frmm2.Show(this);
this.Hide();
}
}
}
Second form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
private System.Timers.Timer tmr;
private Form2 frm2;
private Form1 frm1;
public Form2(Form1 f1)
{
InitializeComponent();
tmr = new System.Timers.Timer();
tmr.Elapsed += new ElapsedEventHandler(OnTimedEvent);
tmr.Interval = 10000;
tmr.Enabled = true;
frm1 = f1;
frm2 = this;
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
tmr.Stop();
MessageBox.Show("Before timer event");
logOut();
MessageBox.Show("After timer event");
}
private void button1_Click(object sender, EventArgs e)
{
logOut();
}
public void logOut()
{
if (tmr != null)
{
tmr.Stop();
tmr = null;
}
/*
* It doesn't work directly. I'll try to do it in another way.
this.Hide();
this.Owner.Show();
this.Owner.Activate();
*/
frm1.Show();
frm1.Activate();
frm2.Close();
}
}
}
Thanks for answers!
Assuming that the
LogOutmethod does something on the UI thread, like closing the form. The problem is that the Elapsed event is raised on a thread pool thread and not on the UI thread.You might try
System.Windows.Forms.Timerinstead ofSystem.Timers.Timersince the former will post it’s elapsed event on the UI thread.