Your code as shown never stops the Timer. Also, to use a System.Timers.Timer and raise an event on a UI thread, you must set the System.Timers.Timer 'SynchronizeObject property.
Here's an example that is based on working code in a WinForms Application:
0. create a reference to a new 'SecondForm:
private SecondForm secondForm = new SecondForm();
1. over-ride OnKeyDown in the main Form code-behind so when Control-K is pressed you present the second Form:
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.K)
{
if (secondForm.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("Valid Login");
}
else
{
MessageBox.Show("Invalid Login");
}
e.Handled = true;
return;
}
base.OnKeyDown(e);
}
2. Here's a sample of the code in the 'SecondForm ... which is shown modally ... that uses a System.Timers.Timer to close the Form after 15 seconds:
namespace YourNameSpace
{
public partial class SecondForm : Form
{
public SecondForm()
{
InitializeComponent();
}
private void SecondForm_Load(object sender, EventArgs e)
{
TheTimer = new System.Timers.Timer();
TheTimer.SynchronizingObject = this;
TheTimer.Elapsed += TheTimer_Elapsed;
TheTimer.Enabled = true;
timerStart = DateTime.Now;
timerEnd = timerStart.AddSeconds(timeLimit);
TheTimer.Start();
TheTimer.Interval = 1000;
}
private int timeLimit = 15;
private System.Timers.Timer TheTimer;
private DateTime timerStart;
private DateTime timerEnd;
private void TheTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (e.SignalTime >= timerEnd)
{
TheTimer.Stop();
this.DialogResult = DialogResult.Abort;
this.Close();
}
}
private void CloseThisForm()
{
this.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private void SecondForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason != CloseReason.UserClosing)
{
this.DialogResult = DialogResult.Cancel;
}
}
}
}
Notes:
1. note the use of the 'DialogResult returned when the 'SecondForm is closed in the main Form.
2. note the use of 'e.CloseReason in the 'SecondForm's FormClosing event handler.