等待winform事件的方法

时间:2013-01-20 19:43:39

标签: c# .net winforms multithreading wait

在我正在开发的程序中,需要一个方法来等待在特定文本框中单击ENTER(通常,调用winform事件)。我知道我会用线程做这个,但不知道如何制作一个能够做到这一点的方法。更具体地说,我不知道如何在线程上调用事件方法,并且不能在Main上调用,因为在调用此方法之前它被阻塞。

停止主线程的方法是:

 void WaitForInput()
 {
     while (!gotInput)
     {
         System.Threading.Thread.Sleep(1);
     }
 }

感谢帮助者。

4 个答案:

答案 0 :(得分:1)

只需订阅文本框的KeyDown(或KeyPress)事件:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        // do your stuff
    }
}

答案 1 :(得分:0)

您可以首先使用如下任务更改要转换的WaitForInput方法:

  private void WaitForInput()
  {
      Task.Factory.StartNew(() =>
          {
              while (!gotInput)
              {
                  System.Threading.Thread.Sleep(1);
              }
              MessageBox.Show("Test");
          });
  }

然后捕获文本框的KeyPressed事件,并将布尔值gotInput的状态更改为true,如下所示:

  private void KeyDown(object sender, KeyPressEventArgs e)
  {
      if (e.KeyChar == (char)13)
          gotInput = true;
  }
祝你好运

答案 2 :(得分:0)

使用.NET 4.5中的async/await关键字。你可以这样做:

CancellationTokenSource tokenSource; // member variable in your Form

// Initialize and wait for input on Form.Load.
async void Form_Load(object sender, EventArgs e)
{
  tokenSource = new CancellationTokenSource();
  await WaitForInput(tokenSource.Token);

  // ENTER was pressed!
}

// Our TextBox has input, cancel the wait if ENTER was pressed.
void TextBox_KeyDown(object sender, KeyEventArgs e)
{
  // Wait for ENTER to be pressed.
  if(e.KeyCode != Keys.Enter) return;

  if(tokenSource != null)
    tokenSource.Cancel();
}

// This method will wait for input asynchronously.
static async Task WaitForInput(CancellationToken token)
{
  await Task.Delay(-1, token); // wait indefinitely
}

答案 3 :(得分:0)

目前我遇到了一台上面装有XP的恐龙电脑(.NET 2008,直到4月才能升级)。我最终得到了评论的解决方案,并且主线程等待并运行线程上的条目。 谢谢!