且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#等待用户输入然后继续代码

更新时间:2022-12-08 16:20:49

如果这是一个winforms应用程序(MessageBox.Show表示它是),那么命中空格将触发事件取决于哪个控件具有焦点。

if this is a winforms application (the "MessageBox.Show" says that it is) then hitting space will trigger an event depending on which control has focus.
private void form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == ' ')
       ps.AddScript("netsh trace stop");
}





问题是你已声明不能接受新事件。我想这是因为button3_Click事件继续运行一段时间,阻止其他事件。



我建议你看一下线程和异步方法。这里有一种方式(未经过全面测试)





The problem is that you have stated that you cannot accept new events. I imagine that this is because the button3_Click event continues to run for some time, blocking other events.

I suggest you look at Threading and Async methods. Here one way (not fully tested)

private PowerShell ps = new PowerShell { };
private BackgroundWorker backgroundWorker = new BackgroundWorker();
private bool isPsRunning = false;

public void button3_Click(object sender, EventArgs e)
{
    backgroundWorker.DoWork +=backgroundWorker_DoWork;
    backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
    backgroundWorker.RunWorkerAsync();

}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    isPsRunning = false;
}
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    isPsRunning = true;
    ps.AddScript("netsh trace start persistent=yes capture=yes tracefile=" + progpath + @"\nettrace.etl");
}
private void form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (isPsRunning && e.KeyChar == ' ')
        ps.AddScript("netsh trace stop");
}