アプリケーション内でプロセスを起動しようとしています。以下のコードは、メインGUIのボタンをクリックするとメモ帳を起動するだけです。これで、メモ帳を起動するとボタンが無効になります。プロセスをサブスクライブしました。メモ帳アプリケーションが閉じたときに通知を受け取るために終了しました。通知を受け取ったら、ボタンを再度有効にします。
ただし、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;
}
}
}