codingguy3000
codingguy3000

Reputation: 2845

C# how do I pause my program and wait for keyboard input from within a WinForm

I have a C# 2008 Winform application and I'm in the middle of a loop. I'm displaying a date to the user and I want them to tell me the day of the week that this date falls on. For example 6/22/2010 is displayed and the user needs to press t.

What I'm stuck on is how do I pause my application and wait for keyboard input? I want to respond to Esc, m, t, w, h, f, s, u and nothing else. All other key presses will be ignored.

In a console application it would be Console.ReadLine(). But how would I do this within a Winform application?

Thanks

Upvotes: 2

Views: 3577

Answers (5)

Henk Holterman
Henk Holterman

Reputation: 273784

You've got the concept wrong, a Windows program is always in a loop, waiting.

So you'll have to think about what input to accept and what to block. You can Cancel a FormClose event for example (but please, leave the user something to get out).

To implement your scheme, use the concept of 'state', after the right input you advance to the next state.

Upvotes: 2

tanascius
tanascius

Reputation: 53964

When you need some information during a calcultion (the loop in your case), you can use a callback method to get this information.

int Calculate( Func<DateTime, string> callback )
{
  var result = callback( dateTime );
}

The caller of this method has to provide a callback that returns the requested value. When the calculation is started in a form, this form could pop up a dialog to ask the user for input. And this could happen in the callback.

EDIT:
Do you know of the DateTime.DayOfWeek property? Maybe you can skip the user dialog at all.

Upvotes: 1

ChrisF
ChrisF

Reputation: 137188

To read a key you need to respond to the KeyDown event.

Then in the handler have something like:

if (e.KeyCode == Keys.M)
{

}

Though you'd probably want a switch statement rather than a series of ifs.

You'd have to think about how you presented the date to the user as well, if it's on the main form or in a model dialog (as others have suggested).

Upvotes: 2

Martin Milan
Martin Milan

Reputation: 6390

You could perhaps use a modal dialog...

Trying to think of a better solution in terms of presentation...

Upvotes: 3

Greg B
Greg B

Reputation: 14898

Spawn a modal dialog box requesting the input.

Upvotes: 2

Related Questions