2015-03-30 142 views
1

我只對C#語言有一個基本的瞭解,但我很困擾,我的程序使用Powershell來執行任務。C#等待用戶輸入,然後繼續輸入代碼

我的具體問題是我無法附加另一個事件處理程序,它可以在用戶點擊一個按鈕後監聽按鍵,我會解釋。

  1. 用戶點擊按鈕
  2. 網絡跟蹤開始使用的powershell(用戶控制何時停止跟蹤)
  3. 我的臨時解決方法是,以顯示一個消息,當該閉合..
  4. 停止網絡跟蹤

是否有反正我可以代替我的消息框,用戶可以按空間停止跟蹤?

謝謝你的時間和事先幫助。

public void button3_Click(object sender, EventArgs e) 
    { 

/////////// 

ps.AddScript("netsh trace start persistent=yes capture=yes tracefile=" + progpath + @"\nettrace.etl"); 

ps.Invoke(); 

MessageBox.Show("Press OK to stop the trace"); 

ps.AddScript("netsh trace stop"); 

///////// 

} 

回答

1

答案由Andy Lanng在代碼項目中提供; http://www.codeproject.com/Questions/892139/Csharp-Wait-for-user-input-then-continue-with-code

如果這是一個winforms應用程序(「MessageBox.Show」表示它是),那麼觸擊空間將觸發一個事件,具體取決於哪個控件具有焦點。 隱藏複製代碼

private void form1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (e.KeyChar == ' ') 
     ps.AddScript("netsh trace stop"); 
} 

的問題是,你說,你不能接受新的事件。我想這是因爲button3_Click事件繼續運行一段時間,阻止其他事件。

我建議你看看線程和異步方法。這裏的一種方式(不完全測試)

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

    public void button3_Click(object sender, EventArgs e) 
    { 

     backgroundWorker.DoWork +=backgroundWorker_DoWork; 

     backgroundWorker.RunWorkerAsync(); 

    } 
    void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) 
    { 
     ps.AddScript("netsh trace start persistent=yes capture=yes tracefile=" + progpath + @"\nettrace.etl"); 

     ps.Invoke(); 
    } 
    private void form1_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if (e.KeyChar == ' ') 
      ps.AddScript("netsh trace stop"); 
    } 

你需要做一些修改此作爲調整if語句以及其中PS聲明等工作。

1

您可以將按鈕作爲切換嗎?例如:

private static bool tracing = false; 

public void button3_Click(object sender, EventArgs e) 
{ 
    if (tracing) 
    { 
     ps.AddScript("netsh trace stop"); 
     button3.Text = "Begin trace"; 
     ps.Invoke(); 
    } 
    else 
    { 
     ps.AddScript("netsh trace start persistent=yes capture=yes tracefile=" + 
      progpath + @"\nettrace.etl"); 
     button3.Text = "Stop trace"; 
    }  

    tracing = !tracing; 
} 
+0

嗨Rufus, 這當然是一種我沒有考慮過的方法,確實做這項工作! 謝謝你的幫助:) – Matt416 2015-03-30 22:56:28

+0

嗨,魯弗斯,我沒有標記你的答案。我想用我原來的計劃去!抱歉。 – Matt416 2015-03-31 11:54:11

+0

這是什麼計劃? – 2015-04-02 02:47:02