如何在获胜应用程序中暂停执行并等待按键

本文关键字:执行 等待 暂停 获胜 应用程序 | 更新日期: 2023-09-27 18:20:53

我正在使用c#实现一个调试器(在VS2012--.Net 4.5上工作),它应该如下工作:(这是一个使用msscript.ocx控件的vbscript调试器)

在具有断点的行上,它应该等待{F5}键,在具有{F5}键后,它应该移动到下一个代码行。

现在的问题是,在调试方法中(此方法在遇到断点时调用)在循环中不断移动,检查设置为true的静态变量(控件上的按键事件将此静态变量设置为true)。

应用程序没有响应,我不得不停止它。

代码如下:

以下代码在TextBox的KeyPress事件中实现:每当它接收到{F5}键时,它就会在静态变量中设置为true。

static bool dVar;
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;
}
}

现在,当遇到断点时,下面的函数被称为

    public void DebugIT()
    {
        dVar=false
            //Waits for the  {F5} key press by checking for the static variable 
           //The Application goes Un-Responsive on this Loop and stops accepting keys
            while (dVar!=true)
            {
                System.Threading.Thread.Sleep(1000); 
            }           

        }

    }

这里的问题是,当它进入while循环时,它停止接受按键,并且没有响应。

需要一种暂停代码执行的方式,直到它收到所需的按键为止。

我们可以有一个单独的线程来检查{F5}按键,并且不会使应用程序失去响应能力吗。

有人能帮忙吗?

如何在获胜应用程序中暂停执行并等待按键

以下是如何做到这一点的示例
如果你想让这个确切的代码工作,创建一个新表单,并在上面拖放两个按钮和一个文本框

public partial class Form1 : Form
{
    ManualResetEvent man = new ManualResetEvent(false);
    public Form1()
    {
        InitializeComponent();
        button1.Click += button1_Click;
        button2.Click += button2_Click;
    }
    private async void button1_Click(object sender, EventArgs e)
    {
        textBox1.Enabled = false;//Do some work before waiting
        await WaitForF5();       //wait for a button click or a key press event or what ever you want
        textBox1.Enabled = true; //Continue
    }
    private Task WaitForF5()
    {
       return Task.Factory.StartNew(() =>
        {
            man.WaitOne();
            man.Reset();
        }
        );
    }
    private void button2_Click(object sender, EventArgs e)
    {
        man.Set();
    }
}

在上面的示例中,当您单击按钮1时,文本框将被禁用,当您按下第二个按钮时,将再次启用。这是在不阻塞UI 的情况下完成的

您需要将DoEvents添加到while循环中。请参阅MSDN 中的示例