1

我有以下情况

kl.KeyDown += CheckPwd;
while(flag)
   System.Windows.Forms.Application.DoEvents();

//continue other code based on "Success"

//This will be called for every keydown
void CheckPwd(object sender, KeyEventArgs e)
{
   //some code here
   if(....)
   {
       flag = true;
       Success = true;   
       kl.KeyDown -= CheckPwd;   
   }
   else
   {
       flag = true;
       Success = false;
       kl.KeyDown -= CheckPwd;
   }
}

在这里我想避免使用Application.DoEvents(). 我尝试使用ManualResetEvent,但是当我调用WaitOne()它时,它阻塞了当前线程,并导致这个,CheckPwd没有启动。我怎样才能做到这一点?

4

1 回答 1

0

创建一个新Success事件,当您达到成功条件时触发它,然后将您需要在 Success 上执行的代码放入该事件的事件处理程序中:

定义事件:

public event Action Success;

附加处理程序:

kl.KeyDown += CheckPwd;
Success += DoSuccessStuff;

触发事件:

void CheckPwd(object sender, KeyEventArgs e)
{
   //some code here
   if(...)
   {
       flag = true;
       Success = true;   
       kl.KeyDown -= CheckPwd;   
       if(Success != null) Success();
   }
   //...
于 2013-09-25T14:22:18.430 回答