Mahapps ProgressRing WPF C#

时间:2017-04-19 04:26:05

标签: c# wpf xaml windows-applications

我尝试在cmd上执行命令时激活进度响铃,按钮在执行命令时保持按下并在进程完成时释放但是当进程仍在运行时我无法激活进度环,看起来像WaitForExit对我不起作用。

 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");
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

您应该在后台线程上调用阻塞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());
    }
}