Timer Control in C# windows Form -
i using onkeypress event , timer execute method. have textbox, want allow user type server name in text box. traditionally events fires on every key press, put method in timer elapsed events , want timer fire action when user wait 5 seconds. below 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 above, want timer fire elapsed event if instance of timer not running (i.e ignore key press before 5 seconds interval of timer). stop timer after execution complete in 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 timer elapsed event each key type regardless of condition. how make ignore keys type when user did not leave 5 seconds interval?
the problem making new timer instance on every click fired after 5 seconds. other timers stop if disable/dispose existing timers.
if (atimer != null) { atimer.stop(); atimer.dispose(); atimer = null; } 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; }
Comments
Post a Comment