Search code examples
c#multithreadingkeypress

How to accept a keypress with separate thread?


I am implementing a debugger using c#, it should work as below: (This is a vbscript debugger which is using msscript.ocx control)

On the line with breakpoint it should wait for the {F5} key and upon having the {F5} key it should move to next code line.

Now the problem is that in the debug method(This method is called upon hitting breakpoint) keeps on moving in the loop checking for the static variable set as true ( The key-press event on the control sets this static variable as true).

The application goes un-responsive and i have to stop it.

Here goes the code for it:

Following code is written for the control to accept a {F5} key on the control(Say a textbox control)

private void fctb_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.F5)
{
    //Setting the static variable true when the control recieves a {F5} key
    dVar = true;
}
}

The other method which runs after the breakpoint is hit checks for dVar value before proceeding: It goes like below:

while (!dVar)
{
System.Threading.Thread.Sleep(100); 
}

The issue here is that when it enter the while loop it stops accepting the key-presses and goes unresponsive.

Need a way that suspends the code execution till time it receives a desired key-press.

Or

Can we have a separate thread which checks for the {F5} key press and does not make the application un-Responsive.

Can anyone please help?


Solution

  • Really difficult to make sense out of the question and answer.

    First, use F10 for the step key, that's pretty standard nowadays.

    To have program lock on a key press, you can use something like this:

    while (Console.ReadKey().Key != ConsoleKey.F11);
    

    This is fine because it will not loop. The ReadKey() method suspends execution until a key is actually pressed. So no CPU resources are wasted here.


    EDIT: windows forms with static variable

    In your comment you've posted this code:

    private void fctb_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.F5)
        {
            dVar = true;
        }
    }
    

    All you need to do now is reset the value on the other method/thread as soon as you handle the event:

    // some code...
    
    while (!dVar)
    {
        System.Threading.Thread.Sleep(100); // don't ever loop without throttling CPU down
    }
    
    dVar = false; // event handled
    
    // some code...