2

我正在尝试在应用程序中启动一个进程。下面的代码只是在单击主 GUI 的按钮时启动记事本。现在,当启动记事本时,该按钮被禁用。我订阅了 Process.Exited 甚至在记事本应用程序关闭时接收通知。收到通知后,我想再次重新启用该按钮。

但是,当我调用 button1.IsEnabled = true; 时代码崩溃了。似乎 Process.Exit 不是主 GUI 线程的一部分,因此当我尝试在其中更新 GUI 时它崩溃了。此外,当我调试时,我没有收到任何异常说我正在尝试从外部访问主线程或其他东西。

有没有办法在子进程退出时通知 GUI?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Diagnostics;

namespace ProcessWatch
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Process pp = null;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            pp = new Process();
            pp.EnableRaisingEvents = true;
            pp.Exited += new EventHandler(pp_Exited);
            ProcessStartInfo oStartInfo = new ProcessStartInfo();
            oStartInfo.FileName = "Notepad.exe";
            oStartInfo.UseShellExecute = false;
            pp.StartInfo = oStartInfo;
            pp.Start();
            button1.IsEnabled = false;
        }

        void pp_Exited(object sender, EventArgs e)
        {
            Process p = sender as Process;
            button1.IsEnabled = true;               
        }
    }
}
4

1 回答 1

1

尝试以下操作:

void pp_Exited(object sender, EventArgs e){ 
   Dispatcher.BeginInvoke(new Action(delegate {    
      button1.IsEnabled = true;       
   }), System.Windows.Threading.DispatcherPriority.ApplicationIdle, null);
}
于 2011-01-27T20:15:00.573 回答