Thursday, 15 August 2013

Timer Control in C# windows Form

Timer Control in C# windows Form

I am using onkeyPress event and a timer to execute a method. I have a
textbox, i want allow user to type their server name in the text box.
Traditionally events fires on every key press, but i put my method in
timer elapsed events and want the timer to fire the action only when the
user wait for five seconds. Below is my timer.
private void tbServer_KeyPress(object sender, KeyPressEventArgs e)
{
//atimer.Stop();
atimer = new System.Timers.Timer();
atimer.Interval = 5000;
atimer.AutoReset = false;
if (atimer.Enabled)
{
return;
}
else
{
atimer.Elapsed += new
System.Timers.ElapsedEventHandler(OnTimedEvent);
atimer.Enabled = true;
}
}
From the above, I want my timer to fire the elapsed event only if another
instance of the timer is not running (i.e ignore any key press before the
five seconds interval of timer). I stop my timer after execution complete
in the elapsed timer event below
private void OnTimedEvent(object source,
System.Timers.ElapsedEventArgs e)
{
if (ping(tbServer.Text, 1))
{
string txt = "Server Matched";
SetText(txt, true);
atimer.Enabled = false;
}
else
{
string txt = " Invalid Server Address";
SetText(txt, false);
atimer.Enabled = false;
}
}
The above code rises the timer elapsed event for each key type regardless
of the condition. How do I make it ignore the keys type when user did not
leave a 5 seconds interval?

No comments:

Post a Comment