1

I have a following situation

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;
   }
}

Here I want to avoid using Application.DoEvents(). I tried using ManualResetEvent, but when I call WaitOne() it is blocking current thread, and causing this, CheckPwd is not firing up. How can I achieve this?

sashkello
  • 17,306
  • 24
  • 81
  • 109
Rajeev
  • 843
  • 2
  • 11
  • 22
  • 3
    Appears to be a [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Tell us what you're trying to achieve. – Sriram Sakthivel Sep 25 '13 at 14:13
  • http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx – cadrell0 Sep 25 '13 at 14:14
  • @SriramSakthivel here i want to avoid Application.DoEvents() but achive same result. – Rajeev Sep 25 '13 at 14:15
  • 1
    Your "success" code should simply be in the `CheckPwd` method, rather than in your earlier section of code, so that you don't *need* to "wait" for the event to be fired. – Servy Sep 25 '13 at 14:16
  • @Servy thanks, but i have to do different work(success code) from different places, actually i am using kl.KeyDown += CheckPwd; from different places – Rajeev Sep 25 '13 at 14:18
  • possible duplicate of [Where is the Application.DoEvents() in WPF?](http://stackoverflow.com/questions/4502037/where-is-the-application-doevents-in-wpf) – H H Sep 25 '13 at 14:22
  • @HenkHolterman He has said he is looking for a more appropriate approach, rather than using a direct equivalent of `DoEvents`... – Servy Sep 25 '13 at 14:23
  • @Servy - not totally clear but you're probably right. – H H Sep 25 '13 at 14:27
  • @Rajeev - this would be much clearer in terms of what you want, now it is in pieces of a (broken) solution. – H H Sep 25 '13 at 14:27
  • `async`/`await` removes the need for `DoEvents` – Ben Voigt Sep 25 '13 at 14:28

1 Answers1

0

Create a new Success event, fire it when you hit your success condition, and then put the code you need to execute on Success in an event handler for that event:

define the event:

public event Action Success;

Attach the handler:

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

Fire the event:

void CheckPwd(object sender, KeyEventArgs e)
{
   //some code here
   if(...)
   {
       flag = true;
       Success = true;   
       kl.KeyDown -= CheckPwd;   
       if(Success != null) Success();
   }
   //...
Servy
  • 202,030
  • 26
  • 332
  • 449