2017-04-19 34 views
0

在cmd上执行命令时,我试图激活进度环,当命令执行时按钮保持按下状态,当进程完成时释放按钮,但当进程仍然处于活动状态时,我无法启动进程环运行,似乎像WaitForExit不适合我。Mahapps ProgressRing WPF C#

private void Button_Click(object sender, RoutedEventArgs e) 
    { 

     if (ComboBox.Text == "") 
     { 
      MessageBox.Show("Select a drive"); 
     } 
     else 
     { 
      try 
      { 
       ProgressRing.IsActive=true; 
       Process cmd = new Process(); 
       cmd.StartInfo.FileName = "cmd.exe"; 
       cmd.StartInfo.RedirectStandardInput = true; 
       cmd.StartInfo.RedirectStandardOutput = true; 
       cmd.StartInfo.CreateNoWindow = true; 
       cmd.StartInfo.UseShellExecute = false; 
       cmd.Start(); 
       cmd.StandardInput.WriteLine("attrib -r -s -h " + ComboBox.Text + "*.* /s /d"); 
       cmd.StandardInput.Flush(); 
       cmd.StandardInput.Close();  
       cmd.WaitForExit(); 
       ProgressRing.IsActive=false; 
      } 
      catch (Exception i) 
      { 
       Console.WriteLine("{0} Exception caught.", i); 
       MessageBox.Show("Error"); 
      } 
     } 
    } 

回答

0

您应该在后台线程上调用阻塞方法WaitForExit。 UI线程不能同时显示您的ProgressRing,并等待该过程同时完成。试试这个:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    if (ComboBox.Text == "") 
    { 
     MessageBox.Show("Select a drive"); 
    } 
    else 
    { 
     ProgressRing.IsActive = true; 
     string text = ComboBox.Text; 
     Task.Factory.StartNew(() => 
     { 
      Process cmd = new Process(); 
      cmd.StartInfo.FileName = "cmd.exe"; 
      cmd.StartInfo.RedirectStandardInput = true; 
      cmd.StartInfo.RedirectStandardOutput = true; 
      cmd.StartInfo.CreateNoWindow = true; 
      cmd.StartInfo.UseShellExecute = false; 
      cmd.Start(); 
      cmd.StandardInput.WriteLine("attrib -r -s -h " + text + "*.* /s /d"); 
      cmd.StandardInput.Flush(); 
      cmd.StandardInput.Close(); 
      cmd.WaitForExit(); 
     }).ContinueWith(task => 
     { 
      ProgressRing.IsActive = false; 
      if (task.IsFaulted) 
      { 
       Console.WriteLine("{0} Exception caught.", task.Exception); 
       MessageBox.Show("Error"); 
      } 
     }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); 
    } 
} 
+0

谢谢你它的工作非常好!我试图让一个线程设置进度IsActive属性,而不是执行cmd命令 –