I have a C# .NET 3.5 app that prompts for a username and a PIN. I'd like the app to automatically reset if no PIN is entered for x seconds. If a key is pressed within x seconds, then the timer should reset to 0 and start again. I've searched around and found various methods for doing this, using a timer, thread.wait, but I haven't found something that was an example of what I'm trying to accomplish. I think the solution will involve using multiple threads, but I've never had to do this before so I'm not sure where to start on this.
2 Answers
You could use the example here which uses the IAsyncResult interface and Action to do it. I myself have used it and it works like a charm. To simplify things just use it as in the example below
Action wrappedAction = () =>
{
// show your input
};
IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
/// the user supplied an input and closed the form
wrappedAction.EndInvoke(result);
}
else
{
// the code has timed out so close your input and throw error
}
Doesn't need to be that clever this, unless it's a behaviour you are going to reuse a lot. Assuming you are showing this form modally
Put a timer on your form (disabled) enable when the form is shown.
Add keydown/keypress eventhandlers to the boxes that could have focus In them restart the timer
If the timer event fires close the form returning a suitable DialogResult Cancel should do it.
Seeing as you reset on keypress, little point in having another thread. If you weren't resetting then M Patel's answer is the way to go, unless you want to reinvent a lot of wheels

- 20,172
- 3
- 31
- 39
-
I'll try this method. I'm not closing the form, it remains open and I simply reset some controls buy changing visibility and text properties. – Kerberos42 Jan 23 '13 at 00:28
-
That worked perfectly, thanks! Just a couple lines of code too! Learn something new every day – Kerberos42 Jan 23 '13 at 01:42
-
It's simple but it's maintenance intensive. For many forms or many changes to a form (think tying in an other edit box, but forgot to hook up the keypress event). Then it can become a bit of a pain, but making something clever and reusable has it's own cost. Making teh timeout value a parameter is a worthwhile improvement. – Tony Hopkinson Jan 23 '13 at 16:45
-
Thankfully this is a VERY simple form. One textbox that changes state between accepting customer id and a pin, so this is a perfect solution. I did make the timeout a parameter which is great for working out the exact timeout based on user behavior. – Kerberos42 Jan 23 '13 at 21:39