我正在尝试在应用程序中启动进程。下面的代码只需在单击主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;
}
}
}
答案 0 :(得分:1)
尝试以下方法:
void pp_Exited(object sender, EventArgs e){
Dispatcher.BeginInvoke(new Action(delegate {
button1.IsEnabled = true;
}), System.Windows.Threading.DispatcherPriority.ApplicationIdle, null);
}