如何在C# Windows Forms中用Async/Await依次获取用户输入
WinForms中基于Async/Await实现按回车捕获多行TextBox输入
控制台中获取用户输入的代码很简洁:
string input1 = Console.ReadLine(); string input2 = Console.ReadLine();
要在WinForms的多行TextBox控件中,通过Async/Await实现类似逻辑——按下回车键时捕获当前行输入,可按以下方式实现:
实现步骤
- 定义
TaskCompletionSource<string>字段,用于异步等待输入完成信号 - 编写
GetUserInputAsync方法返回可等待任务 - 绑定TextBox的
KeyPress事件,在回车触发时完成任务并返回输入内容
完整代码示例
在Form类中添加以下代码:
// 用于跟踪异步输入任务的完成源 private TaskCompletionSource<string> _inputCompletionSource; // 异步获取用户输入的方法 public Task<string> GetUserInputAsync() { // 重置完成源,确保每次调用都是新的任务 _inputCompletionSource = new TaskCompletionSource<string>(); return _inputCompletionSource.Task; } // TextBox的按键事件处理 private void multiLineTextBox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter) { e.Handled = true; // 阻止默认换行行为,可根据需求改为false var textBox = sender as TextBox; if (textBox == null || _inputCompletionSource == null) return; // 获取当前光标所在的行内容 int currentLineIndex = textBox.GetLineFromCharIndex(textBox.SelectionStart); string currentInput = textBox.Lines[currentLineIndex]; // 手动添加换行(如果需要保留输入历史) textBox.AppendText(Environment.NewLine); // 完成异步任务,返回输入内容 _inputCompletionSource.SetResult(currentInput); _inputCompletionSource = null; } }
使用方式
在需要获取输入的地方(比如按钮点击事件)调用:
private async void startButton_Click(object sender, EventArgs e) { // 等待第一行输入 string input1 = await GetUserInputAsync(); // 可在这里处理第一行输入,比如显示提示 MessageBox.Show($"第一行输入:{input1}"); // 等待第二行输入 string input2 = await GetUserInputAsync(); MessageBox.Show($"第二行输入:{input2}"); }
注意事项
- 确保TextBox的
Multiline属性设为true,AcceptsReturn属性设为true - 若希望按回车时自动换行,可将
e.Handled设为false,无需手动调用AppendText - 多次调用
GetUserInputAsync时,会自动重置任务源,避免任务冲突
内容的提问来源于stack exchange,提问作者Babak Mahmoudabadi
相关产品推荐
相关产品推荐

