[英]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. 我有一个C#2008 Winform应用程序,我正处于循环中。 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. 例如,显示6/22/2010,用户需要按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. 我想回应Esc,m,t,w,h,f,s,u等等。 All other key presses will be ignored. 所有其他按键将被忽略。
In a console application it would be Console.ReadLine(). 在控制台应用程序中,它将是Console.ReadLine()。 But how would I do this within a Winform application? 但是我如何在Winform应用程序中执行此操作?
Thanks 谢谢
You could perhaps use a modal dialog... 您也许可以使用模态对话框......
Trying to think of a better solution in terms of presentation... 试图在演示方面考虑更好的解决方案......
产生请求输入的模态对话框。
To read a key you need to respond to the KeyDown
event. 要读取密钥,您需要响应KeyDown
事件。
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. 虽然你可能想要一个switch语句而不是一系列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). 你必须考虑如何向用户呈现日期,如果它在主窗体或模型对话框中(正如其他人所建议的那样)。
You've got the concept wrong, a Windows program is always in a loop, waiting. 你有这个概念错了,Windows程序总是处于循环中,等待。
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). 例如,您可以取消FormClose事件(但请让用户离开)。
To implement your scheme, use the concept of 'state', after the right input you advance to the next state. 要实现您的方案,请使用“state”的概念,在正确的输入之后,您将前进到下一个状态。
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? 你知道DateTime.DayOfWeek属性吗? Maybe you can skip the user dialog at all. 也许你可以跳过用户对话框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.